/
IteratingSDFReader.java
347 lines (306 loc) · 13 KB
/
IteratingSDFReader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/* Copyright (C) 2003-2007 The Chemistry Development Kit (CDK) project
* 2014 Mark B Vine (orcid:0000-0002-7794-0426)
*
* Contact: cdk-devel@lists.sourceforge.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
* All we ask is that proper credit is given for our work, which includes
* - but is not limited to - adding the above copyright notice to the beginning
* of your source code files, and to any copyright notice that you may distribute
* with programs based on this work.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openscience.cdk.io.iterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IChemObjectBuilder;
import org.openscience.cdk.io.ISimpleChemObjectReader;
import org.openscience.cdk.io.MDLReader;
import org.openscience.cdk.io.MDLV2000Reader;
import org.openscience.cdk.io.MDLV3000Reader;
import org.openscience.cdk.io.formats.IChemFormat;
import org.openscience.cdk.io.formats.IResourceFormat;
import org.openscience.cdk.io.formats.MDLFormat;
import org.openscience.cdk.io.formats.MDLV2000Format;
import org.openscience.cdk.io.formats.MDLV3000Format;
import org.openscience.cdk.io.setting.BooleanIOSetting;
import org.openscience.cdk.io.setting.IOSetting;
import org.openscience.cdk.tools.ILoggingTool;
import org.openscience.cdk.tools.LoggingToolFactory;
/**
* Iterating MDL SDF reader. It allows to iterate over all molecules
* in the SD file, without reading them into memory first. Suitable
* for (very) large SDF files. For parsing the molecules in the
* SD file, it uses the <code>MDLV2000Reader</code> or
* <code>MDLV3000Reader</code> reader; it does <b>not</b> work
* for SDF files with MDL formats prior to the V2000 format.
*
* <p>Example use:
* <pre>
* File sdfFile = new File("../zinc-structures/ZINC_subset3_3D_charged_wH_maxmin1000.sdf");
* IteratingSDFReader reader = new IteratingSDFReader(
* new FileInputStream(sdfFile), DefaultChemObjectBuilder.getInstance()
* );
* while (reader.hasNext()) {
* IAtomContainer molecule = (IAtomContainer)reader.next();
* }
* </pre>
*
* @cdk.module io
* @cdk.githash
*
* @see org.openscience.cdk.io.MDLV2000Reader
* @see org.openscience.cdk.io.MDLV3000Reader
*
* @author Egon Willighagen <egonw@sci.kun.nl>
* @cdk.created 2003-10-19
*
* @cdk.keyword file format, MDL molfile
* @cdk.keyword file format, SDF
* @cdk.iooptions
*/
public class IteratingSDFReader extends DefaultIteratingChemObjectReader<IAtomContainer> {
private BufferedReader input;
private static final ILoggingTool logger = LoggingToolFactory
.createLoggingTool(IteratingSDFReader.class);
private String currentLine;
private IChemFormat currentFormat;
private boolean nextAvailableIsKnown;
private boolean hasNext;
private final IChemObjectBuilder builder;
private IAtomContainer nextMolecule;
private BooleanIOSetting forceReadAs3DCoords;
// if an error is encountered the reader will skip over the error
private boolean skip = false;
// buffer to store pre-read Mol records in
private final StringBuilder buffer = new StringBuilder(10000);
private static final String LINE_SEPARATOR = "\n";
// patterns to match
private static final Pattern MDL_VERSION = Pattern.compile("[vV](2000|3000)");
private static final String SDF_RECORD_SEPARATOR = "$$$$";
private static final String SDF_DATA_HEADER = "> ";
// map of MDL formats to their readers
private final Map<IChemFormat, ISimpleChemObjectReader> readerMap = new HashMap<>(
5);
/**
* Constructs a new IteratingMDLReader that can read Molecule from a given Reader.
*
* @param in The Reader to read from
* @param builder The builder
*/
public IteratingSDFReader(Reader in, IChemObjectBuilder builder) {
this(in, builder, false);
}
/**
* Constructs a new IteratingMDLReader that can read Molecule from a given InputStream.
*
* @param in The InputStream to read from
* @param builder The builder
*/
public IteratingSDFReader(InputStream in, IChemObjectBuilder builder) {
this(new InputStreamReader(in), builder);
}
/**
* Constructs a new IteratingMDLReader that can read Molecule from a given a
* InputStream. This constructor allows specification of whether the reader will
* skip 'null' molecules. If skip is set to false and a broken/corrupted molecule
* is read the iterating reader will stop at the broken molecule. However if
* skip is set to true then the reader will keep trying to read more molecules
* until the end of the file is reached.
*
* @param in the {@link InputStream} to read from
* @param builder builder to use
* @param skip whether to skip null molecules
*/
public IteratingSDFReader(InputStream in, IChemObjectBuilder builder, boolean skip) {
this(new InputStreamReader(in), builder, skip);
}
/**
* Constructs a new IteratingMDLReader that can read Molecule from a given a
* Reader. This constructor allows specification of whether the reader will
* skip 'null' molecules. If skip is set to false and a broken/corrupted molecule
* is read the iterating reader will stop at the broken molecule. However if
* skip is set to true then the reader will keep trying to read more molecules
* until the end of the file is reached.
*
* @param in the {@link Reader} to read from
* @param builder builder to use
* @param skip whether to skip null molecules
*/
public IteratingSDFReader(Reader in, IChemObjectBuilder builder, boolean skip) {
this.builder = builder;
setReader(in);
initIOSettings();
setSkip(skip);
}
@Override
public IResourceFormat getFormat() {
return currentFormat;
}
/**
* Method will return an appropriate reader for the provided format. Each reader is stored
* in a map, if no reader is available for the specified format a new reader is created. The
* {@see ISimpleChemObjectReadr#setErrorHandler(IChemObjectReaderErrorHandler)} and
* {@see ISimpleChemObjectReadr#setReaderMode(DefaultIteratingChemObjectReader)}
* methods are set.
*
* @param format The format to obtain a reader for
* @return instance of a reader appropriate for the provided format
*/
private ISimpleChemObjectReader getReader(IChemFormat format) {
// create a new reader if not mapped
if (!readerMap.containsKey(format)) {
ISimpleChemObjectReader reader;
if (format instanceof MDLV2000Format)
reader = new MDLV2000Reader();
else if (format instanceof MDLV3000Format)
reader = new MDLV3000Reader();
else if (format instanceof MDLFormat)
reader = new MDLReader();
else
throw new IllegalArgumentException("Unexpected format: " + format);
reader.setErrorHandler(this.errorHandler);
reader.setReaderMode(this.mode);
if (currentFormat instanceof MDLV2000Format) {
reader.addSettings(getSettings());
}
readerMap.put(format, reader);
}
return readerMap.get(format);
}
/**
* Returns true if another {@link IAtomContainer} can be read.
*/
@Override
public boolean hasNext() {
if (nextAvailableIsKnown) {
return hasNext;
}
hasNext = false;
nextMolecule = null;
// now try to parse the next Molecule
try {
for (;;) {
currentFormat = (IChemFormat) MDLFormat.getInstance();
int lineNum = 0;
buffer.setLength(0);
while ((currentLine = input.readLine()) != null) {
// still in a molecule
buffer.append(currentLine).append(LINE_SEPARATOR);
lineNum++;
// do MDL molfile version checking
if (lineNum == 4) {
Matcher versionMatcher = MDL_VERSION.matcher(currentLine);
if (versionMatcher.find()) {
currentFormat = "2000".equals(versionMatcher.group(1)) ? (IChemFormat) MDLV2000Format.getInstance()
: (IChemFormat) MDLV3000Format.getInstance();
}
}
if (currentLine.startsWith(SDF_RECORD_SEPARATOR)) {
break;
}
}
logger.debug("MDL file part read: ", buffer);
IAtomContainer molecule = null;
try {
ISimpleChemObjectReader reader = getReader(currentFormat);
reader.setReader(new StringReader(buffer.toString()));
molecule = reader.read(builder.newAtomContainer());
} catch (Exception exception) {
logger.error("Error while reading next molecule: " + exception.getMessage());
logger.debug(exception);
}
if (molecule != null) {
hasNext = true;
nextAvailableIsKnown = true;
nextMolecule = molecule;
return true;
} else if (!skip) {
return false;
} else if (currentLine == null && buffer.length() == 0) {
return false; // EOF
}
// else (skip=true) try next record
}
} catch (IOException exception) {
logger.error("Error while reading next molecule: " + exception.getMessage());
logger.debug(exception);
}
return false;
}
/**
* Indicate whether the reader should skip over SDF records
* that cause problems. If true the reader will fetch the next
* molecule
* @param skip ignore error molecules continue reading
*/
public void setSkip(boolean skip) {
this.skip = skip;
}
/**
* Returns the next {@link IAtomContainer}.
*/
@Override
public IAtomContainer next() {
if (!nextAvailableIsKnown) {
hasNext = hasNext();
}
nextAvailableIsKnown = false;
if (!hasNext) {
throw new NoSuchElementException();
}
return nextMolecule;
}
@Override
public void close() throws IOException {
input.close();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void setReader(Reader reader) {
if (reader instanceof BufferedReader) {
input = (BufferedReader) reader;
} else {
input = new BufferedReader(reader);
}
nextMolecule = null;
nextAvailableIsKnown = false;
hasNext = false;
}
@Override
public void setReader(InputStream reader) {
setReader(new InputStreamReader(reader));
}
private void initIOSettings() {
forceReadAs3DCoords = new BooleanIOSetting("ForceReadAs3DCoordinates", IOSetting.Importance.LOW,
"Should coordinates always be read as 3D?", "false");
addSetting(forceReadAs3DCoords);
}
public void customizeJob() {
fireIOSettingQuestion(forceReadAs3DCoords);
}
}