~ubuntu-branches/ubuntu/trusty/cdk/trusty-proposed

« back to all changes in this revision

Viewing changes to src/org/openscience/cdk/ringsearch/AllRingsFinder.java

  • Committer: Bazaar Package Importer
  • Author(s): Paul Cager
  • Date: 2008-04-09 21:17:53 UTC
  • Revision ID: james.westby@ubuntu.com-20080409211753-46lmjw5z8mx5pd8d
Tags: upstream-1.0.2
ImportĀ upstreamĀ versionĀ 1.0.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* $Revision: 8201 $ $Author: egonw $ $Date: 2007-04-16 10:40:19 +0200 (Mon, 16 Apr 2007) $
 
2
 *
 
3
 * Copyright (C) 2002-2007  Christoph Steinbeck <steinbeck@users.sf.net>
 
4
 *
 
5
 * Contact: cdk-devel@lists.sourceforge.net
 
6
 *
 
7
 * This program is free software; you can redistribute it and/or
 
8
 * modify it under the terms of the GNU Lesser General Public License
 
9
 * as published by the Free Software Foundation; either version 2.1
 
10
 * of the License, or (at your option) any later version.
 
11
 * All we ask is that proper credit is given for our work, which includes
 
12
 * - but is not limited to - adding the above copyright notice to the beginning
 
13
 * of your source code files, and to any copyright notice that you may distribute
 
14
 * with programs based on this work.
 
15
 *
 
16
 * This program is distributed in the hope that it will be useful,
 
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
19
 * GNU Lesser General Public License for more details.
 
20
 *
 
21
 * You should have received a copy of the GNU Lesser General Public License
 
22
 * along with this program; if not, write to the Free Software
 
23
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 
24
 */
 
25
package org.openscience.cdk.ringsearch;
 
26
 
 
27
import org.openscience.cdk.exception.CDKException;
 
28
import org.openscience.cdk.graph.ConnectivityChecker;
 
29
import org.openscience.cdk.graph.SpanningTree;
 
30
import org.openscience.cdk.interfaces.*;
 
31
import org.openscience.cdk.tools.LoggingTool;
 
32
 
 
33
import java.util.ArrayList;
 
34
import java.util.Iterator;
 
35
import java.util.List;
 
36
 
 
37
/**
 
38
 * Finds the Set of all Rings. This is an implementation of the algorithm
 
39
 * published in {@cdk.cite HAN96}. Some of the comments refer to pseudo code
 
40
 * fragments listed in this article. The concept is that a regular molecular
 
41
 * graph is converted into a path graph first, i.e. a graph where the edges are
 
42
 * actually paths, i.e. can list several nodes that are implicitly connecting
 
43
 * the two nodes between the path is formed. The paths that join one endnode
 
44
 * are step by step fused and the joined nodes deleted from the pathgraph. What
 
45
 * remains is a graph of paths that have the same start and endpoint and are
 
46
 * thus rings.
 
47
 *
 
48
 * <p><b>WARNING</b>: This class has now a timeout of 5 seconds, after which it aborts
 
49
 * its ringsearch. The timeout value can be customized by the setTimeout()
 
50
 * method of this class.  
 
51
 *
 
52
 * @author        steinbeck
 
53
 * @cdk.created   2002-06-23
 
54
 * @cdk.module    standard
 
55
 */
 
56
public class AllRingsFinder
 
57
{
 
58
        private final LoggingTool logger = new LoggingTool(AllRingsFinder.class);
 
59
        
 
60
        public boolean debug = false;
 
61
        private long timeout = 5000;
 
62
        private long startTime;
 
63
 
 
64
        /*
 
65
         *  used for storing the original atomContainer for
 
66
         *  reference purposes (printing)
 
67
         */
 
68
        IAtomContainer originalAc = null;
 
69
        List newPaths = new ArrayList();
 
70
        List potentialRings = new ArrayList();
 
71
        List removePaths = new ArrayList();
 
72
 
 
73
 
 
74
        /**
 
75
         *  Returns a ringset containing all rings in the given AtomContainer
 
76
         *
 
77
         *@param  atomContainer     The AtomContainer to be searched for rings
 
78
         *@return                   A RingSet with all rings in the AtomContainer
 
79
         *@exception  CDKException  An exception thrown if something goes wrong or if the timeout limit is reached
 
80
         */
 
81
        public IRingSet findAllRings(IAtomContainer atomContainer) throws CDKException
 
82
        {
 
83
                startTime = System.currentTimeMillis();
 
84
                SpanningTree spanningTree = new SpanningTree(atomContainer);
 
85
                IAtomContainer ringSystems = spanningTree.getCyclicFragmentsContainer();
 
86
                Iterator separateRingSystem = ConnectivityChecker.partitionIntoMolecules(ringSystems).molecules();
 
87
                IRingSet resultSet = atomContainer.getBuilder().newRingSet();
 
88
                while (separateRingSystem.hasNext()) {
 
89
                        resultSet.add(findAllRingsInIsolatedRingSystem((IMolecule)separateRingSystem.next()));
 
90
                }
 
91
                return resultSet;
 
92
        }
 
93
 
 
94
 
 
95
        /**
 
96
         *  Fings the set of all rings in a molecule
 
97
         *
 
98
         *@param  atomContainer     the molecule to be searched for rings
 
99
         *@return                   a RingSet containing the rings in molecule
 
100
         *@exception  CDKException  An exception thrown if something goes wrong or if the timeout limit is reached
 
101
         */
 
102
        public IRingSet findAllRingsInIsolatedRingSystem(IAtomContainer atomContainer) throws CDKException
 
103
        {
 
104
                if (startTime == 0) {
 
105
                        startTime = System.currentTimeMillis();
 
106
                }
 
107
                List paths = new ArrayList();
 
108
                IRingSet ringSet = atomContainer.getBuilder().newRingSet();
 
109
                IAtomContainer ac = atomContainer.getBuilder().newAtomContainer();
 
110
                originalAc = atomContainer;
 
111
                ac.add(atomContainer);
 
112
                doSearch(ac, paths, ringSet);
 
113
                return ringSet;
 
114
        }
 
115
 
 
116
 
 
117
        /**
 
118
         *@param  ac                The AtomContainer to be searched
 
119
         *@param  paths            A vectoring storing all the paths
 
120
         *@param  ringSet           A ringset to be extended while we search
 
121
         *@exception  CDKException  An exception thrown if something goes wrong or if the timeout limit is reached
 
122
         */
 
123
        private void doSearch(IAtomContainer ac, List paths, IRingSet ringSet) throws CDKException
 
124
        {
 
125
                IAtom atom;
 
126
                /*
 
127
                 *  First we convert the molecular graph into a a path graph by
 
128
                 *  creating a set of two membered paths from all the bonds in the molecule
 
129
                 */
 
130
                initPathGraph(ac, paths);
 
131
                logger.debug("BondCount: ", ac.getBondCount());
 
132
                logger.debug("PathCount: ", paths.size());
 
133
                do
 
134
                {
 
135
                        atom = selectAtom(ac);
 
136
                        if (atom != null)
 
137
                        {
 
138
                                remove(atom, ac, paths, ringSet);
 
139
                        }
 
140
                } while (paths.size() > 0 && atom != null);
 
141
                logger.debug("paths.size(): ", paths.size());
 
142
                logger.debug("ringSet.size(): ", ringSet.getAtomContainerCount());
 
143
        }
 
144
 
 
145
 
 
146
        /**
 
147
         *  Removes all external aliphatic chains by chopping them off from the
 
148
         *  ends
 
149
         *
 
150
         *@param  ac                The AtomContainer to work with
 
151
         *@exception  CDKException  An exception thrown if something goes wrong or if the timeout limit is reached
 
152
         */
 
153
        private void removeAliphatic(IAtomContainer ac) throws CDKException
 
154
        {
 
155
                boolean removedSomething;
 
156
                IAtom atom;
 
157
                do
 
158
                {
 
159
                        removedSomething = false;
 
160
                        for (Iterator e = ac.atoms(); e.hasNext(); )
 
161
                        {
 
162
                                atom = (IAtom) e.next();
 
163
                                if (ac.getConnectedBondsCount(atom) == 1)
 
164
                                {
 
165
                                        ac.removeAtomAndConnectedElectronContainers(atom);
 
166
                                        removedSomething = true;
 
167
                                }
 
168
                        }
 
169
                } while (removedSomething);
 
170
        }
 
171
 
 
172
 
 
173
        /**
 
174
         *  Removes an atom from the AtomContainer under certain conditions.
 
175
         *  See {@cdk.cite HAN96} for details
 
176
         *  
 
177
         *
 
178
         *@param  atom              The atom to be removed
 
179
         *@param  ac                The AtomContainer to work on
 
180
         *@param  paths            The paths to manipulate
 
181
         *@param  rings             The ringset to be extended
 
182
         *@exception  CDKException  Thrown if something goes wrong or if the timeout is exceeded
 
183
         */
 
184
        private void remove(IAtom atom, IAtomContainer ac, List paths, IRingSet rings) throws CDKException
 
185
        {
 
186
                Path path1;
 
187
                Path path2;
 
188
                Path union;
 
189
                int intersectionSize;
 
190
                newPaths.clear();
 
191
                removePaths.clear();
 
192
                potentialRings.clear();
 
193
                logger.debug("*** Removing atom " + originalAc.getAtomNumber(atom) + " ***");
 
194
 
 
195
                for (int i = 0; i < paths.size(); i++)
 
196
                {
 
197
                        path1 = (Path) paths.get(i);
 
198
                        if (path1.firstElement() == atom || path1.lastElement() == atom)
 
199
                        {
 
200
                                for (int j = i + 1; j < paths.size(); j++)
 
201
                                {
 
202
                                        //logger.debug(".");
 
203
                                        path2 = (Path) paths.get(j);
 
204
                                        if (path2.firstElement() == atom || path2.lastElement() == atom)
 
205
                                        {
 
206
                                                intersectionSize = path1.getIntersectionSize(path2);
 
207
                                                if (intersectionSize < 3)
 
208
                                                {
 
209
                                                        logger.debug("Joining " + path1.toString(originalAc) + " and " + path2.toString(originalAc));
 
210
                                                        union = Path.join(path1, path2, atom);
 
211
                                                        if (intersectionSize == 1)
 
212
                                                        {
 
213
                                                                newPaths.add(union);
 
214
                                                        } else
 
215
                                                        {
 
216
                                                                potentialRings.add(union);
 
217
                                                        }
 
218
                                                        //logger.debug("Intersection Size: " + intersectionSize);
 
219
                                                        logger.debug("Union: ", union.toString(originalAc));
 
220
                                                        /*
 
221
                                                         *  Now we know that path1 and
 
222
                                                         *  path2 share the Atom atom.
 
223
                                                         */
 
224
                                                        removePaths.add(path1);
 
225
                                                        removePaths.add(path2);
 
226
                                                }
 
227
                                        }
 
228
                                        if (timeout > 0) checkTimeout();
 
229
                                }
 
230
                        }
 
231
                }
 
232
                for (int f = 0; f < removePaths.size(); f++)
 
233
                {
 
234
                        paths.remove(removePaths.get(f));
 
235
                }
 
236
                for (int f = 0; f < newPaths.size(); f++)
 
237
                {
 
238
                        paths.add(newPaths.get(f));
 
239
                }
 
240
                detectRings(potentialRings, rings, originalAc);
 
241
                ac.removeAtomAndConnectedElectronContainers(atom);
 
242
                logger.debug("\n" + paths.size() + " paths and " + ac.getAtomCount() + " atoms left.");
 
243
        }
 
244
 
 
245
 
 
246
        /**
 
247
         *  Checks the paths if a ring has been found
 
248
         *
 
249
         *@param  paths   The paths to check for rings
 
250
         *@param  ringSet  The ringset to add the detected rings to
 
251
         *@param  ac       The AtomContainer with the original structure
 
252
         */
 
253
        private void detectRings(List paths, IRingSet ringSet, IAtomContainer ac)
 
254
        {
 
255
                Path path;
 
256
                IRing ring;
 
257
                int bondNum;
 
258
                IAtom a1, a2 = null;
 
259
                for (int f = 0; f < paths.size(); f++)
 
260
                {
 
261
                        path = (Path) paths.get(f);
 
262
                        if (path.size() > 3 && path.lastElement() == path.firstElement())
 
263
                        {
 
264
                                logger.debug("Removing path " + path.toString(originalAc) + " which is a ring.");
 
265
                                path.removeElementAt(0);
 
266
                                ring = ac.getBuilder().newRing();
 
267
                                for (int g = 0; g < path.size() - 1; g++)
 
268
                                {
 
269
                                        a1 = (IAtom) path.elementAt(g);
 
270
                                        a2 = (IAtom) path.elementAt(g + 1);
 
271
                                        ring.addAtom(a1);
 
272
                                        bondNum = ac.getBondNumber(a1, a2);
 
273
                                        //logger.debug("bondNum " + bondNum);
 
274
                                        ring.addBond(ac.getBond(bondNum));
 
275
                                }
 
276
                                ring.addAtom(a2);
 
277
                                a1 = (IAtom) path.elementAt(0);
 
278
                                a2 = (IAtom) path.elementAt(path.size()-1);
 
279
                                ring.addAtom(a1);
 
280
                                bondNum = ac.getBondNumber(a1, a2);
 
281
                                //logger.debug("bondNum " + bondNum);
 
282
                                ring.addBond(ac.getBond(bondNum));
 
283
 
 
284
                                /*
 
285
                                 * The following code had a problem when two atom in the ring 
 
286
                                 * found are connected the in orignal graph but do not belong
 
287
                                 * to this particular ring.
 
288
                                 IBond[] bonds = ac.getBonds();
 
289
                                for (int g = 0; g < bonds.length; g++)
 
290
                                {
 
291
                                        bond = bonds[g];
 
292
                                        if (ring.contains(bond.getAtom(0)) && ring.contains(bond.getAtom(1)))
 
293
                                        {
 
294
                                                ring.addBond(bond);
 
295
                                        }
 
296
                                }*/
 
297
                                ringSet.addAtomContainer(ring);
 
298
                        }
 
299
                }
 
300
        }
 
301
 
 
302
 
 
303
        /**
 
304
         *  Initialized the path graph
 
305
         *  See {@cdk.cite HAN96} for details
 
306
         *
 
307
         *@param  ac      The AtomContainer with the original structure
 
308
         *@param  paths  The paths to initialize
 
309
         */
 
310
        private void initPathGraph(IAtomContainer ac, List paths)
 
311
        {
 
312
                Path path;
 
313
 
 
314
        Iterator bonds = ac.bonds();
 
315
        while (bonds.hasNext()) {
 
316
            IBond bond = (IBond) bonds.next();                    
 
317
                        path = new Path(bond.getAtom(0), bond.getAtom(1));
 
318
                        paths.add(path);
 
319
                        logger.debug("initPathGraph: " + path.toString(originalAc));
 
320
                }
 
321
        }
 
322
 
 
323
 
 
324
        /**
 
325
         *  Selects an optimal atom for removal
 
326
         *  See {@cdk.cite HAN96} for details
 
327
         *
 
328
         *@param  ac  The AtomContainer to search
 
329
         *@return     The selected Atom
 
330
         */
 
331
        private IAtom selectAtom(IAtomContainer ac)
 
332
        {
 
333
                int minDegree = 999;
 
334
                // :-)
 
335
                int degree;
 
336
                IAtom minAtom = null;
 
337
                IAtom atom;
 
338
                for (int f = 0; f < ac.getAtomCount(); f++)
 
339
                {
 
340
                        atom = ac.getAtom(f);
 
341
                        degree = ac.getConnectedBondsCount(atom);
 
342
 
 
343
                        if (degree < minDegree)
 
344
                        {
 
345
                                minAtom = atom;
 
346
                                minDegree = degree;
 
347
                        }
 
348
                }
 
349
 
 
350
                return minAtom;
 
351
        }
 
352
 
 
353
 
 
354
        /**
 
355
         *  Checks if the timeout has been reached and throws an 
 
356
         *  exception if so. This is used to prevent this AllRingsFinder
 
357
         *  to run for ages in certain rare cases with ring systems of
 
358
         *  large size or special topology.
 
359
         *
 
360
         *@exception  CDKException  The exception thrown in case of hitting the timeout
 
361
         */
 
362
        public void checkTimeout() throws CDKException
 
363
        {
 
364
                if (startTime == 0) return;
 
365
                long time = System.currentTimeMillis();
 
366
                if (time - startTime > timeout)
 
367
                {
 
368
                        throw new CDKException("Timeout for AllringsFinder exceeded");
 
369
                }
 
370
        }
 
371
 
 
372
 
 
373
        /**
 
374
         *  Sets the timeout value in milliseconds of the AllRingsFinder object
 
375
         *  This is used to prevent this AllRingsFinder
 
376
         *  to run for ages in certain rare cases with ring systems of
 
377
         *  large size or special topology
 
378
         *
 
379
         *@param  timeout  The new timeout value
 
380
   * @return a reference to the instance this method was called for
 
381
         */
 
382
        public AllRingsFinder setTimeout(long timeout)
 
383
        {
 
384
                this.timeout = timeout;
 
385
    return this;
 
386
        }
 
387
 
 
388
 
 
389
        /**
 
390
         *  Gets the timeout values in milliseconds of the AllRingsFinder object
 
391
         *
 
392
         *@return    The timeout value
 
393
         */
 
394
        public long getTimeout()
 
395
        {
 
396
                return timeout;
 
397
        }
 
398
}
 
399