-
Notifications
You must be signed in to change notification settings - Fork 154
/
IteratingMDLReader.java
307 lines (277 loc) · 11 KB
/
IteratingMDLReader.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
/* $Revision$ $Author$ $Date$
*
* Copyright (C) 2003-2007 The Chemistry Development Kit (CDK) project
*
* 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.NoSuchElementException;
import org.openscience.cdk.annotations.TestMethod;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.interfaces.IChemObject;
import org.openscience.cdk.interfaces.IMolecule;
import org.openscience.cdk.interfaces.IChemObjectBuilder;
import org.openscience.cdk.io.ISimpleChemObjectReader;
import org.openscience.cdk.io.MDLV2000Reader;
import org.openscience.cdk.io.ReaderFactory;
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.listener.IChemObjectIOListener;
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");
* IteratingMDLReader reader = new IteratingMDLReader(
* new FileInputStream(sdfFile), NewDefaultChemObjectBuilder.getInstance()
* );
* while (reader.hasNext()) {
* IMolecule molecule = (IMolecule)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
*/
public class IteratingMDLReader extends DefaultIteratingChemObjectReader implements IChemObjectIOListener {
private BufferedReader input;
private static ILoggingTool logger =
LoggingToolFactory.createLoggingTool(IteratingMDLReader.class);
private String currentLine;
private IChemFormat currentFormat;
private final ReaderFactory factory = new ReaderFactory();
private boolean nextAvailableIsKnown;
private boolean hasNext;
private IChemObjectBuilder builder;
private IMolecule nextMolecule;
private BooleanIOSetting forceReadAs3DCoords;
/**
* Constructs a new IteratingMDLReader that can read Molecule from a given Reader.
*
* @param in The Reader to read from
* @param builder The builder
*/
public IteratingMDLReader(Reader in, IChemObjectBuilder builder) {
this.builder = builder;
setReader(in);
initIOSettings();
}
/**
* Contructs a new IteratingMDLReader that can read Molecule from a given InputStream.
*
* @param in The InputStream to read from
* @param builder The builder
*/
public IteratingMDLReader(InputStream in, IChemObjectBuilder builder) {
this(new InputStreamReader(in), builder);
}
@TestMethod("testGetFormat")
public IResourceFormat getFormat() {
return currentFormat;
}
/**
* Returns true if another IMolecule can be read.
*/
public boolean hasNext() {
if (!nextAvailableIsKnown) {
hasNext = false;
// now try to parse the next Molecule
try {
if ((currentLine = input.readLine()) != null) {
currentFormat = (IChemFormat)MDLFormat.getInstance();
StringBuffer buffer = new StringBuffer();
while (currentLine != null && !currentLine.equals("M END")) {
// still in a molecule
buffer.append(currentLine);
buffer.append(System.getProperty("line.separator"));
currentLine = input.readLine();
// do MDL molfile version checking
if (currentLine.contains("V2000") || currentLine.contains("v2000")) {
currentFormat = (IChemFormat)MDLV2000Format.getInstance();
} else if (currentLine.contains("V3000") || currentLine.contains("v3000")) {
currentFormat = (IChemFormat)MDLV3000Format.getInstance();
}
}
buffer.append(currentLine);
buffer.append(System.getProperty("line.separator"));
logger.debug("MDL file part read: ", buffer);
ISimpleChemObjectReader reader = factory.createReader(currentFormat);
reader.setReader(new StringReader(buffer.toString()));
if (currentFormat instanceof MDLV2000Format) {
reader.addChemObjectIOListener(this);
((MDLV2000Reader)reader).customizeJob();
}
nextMolecule = (IMolecule)reader.read(builder.newInstance(IMolecule.class));
// note that a molecule may have 0 atoms, but still
// be useful (by having SD tags for example), so just
// check for null'ness rather than atom count
hasNext = nextMolecule != null;
// now read the data part
currentLine = input.readLine();
readDataBlockInto(nextMolecule);
} else {
hasNext = false;
}
} catch (Exception exception) {
logger.error("Error while reading next molecule: " +
exception.getMessage());
logger.debug(exception);
hasNext = false;
}
if (!hasNext) nextMolecule = null;
nextAvailableIsKnown = true;
}
return hasNext;
}
private void readDataBlockInto(IMolecule m) throws IOException {
String fieldName = null;
while (currentLine != null && !(currentLine.trim().equals("$$$$"))) {
logger.debug("looking for data header: ", currentLine);
String str = new String(currentLine);
if (str.startsWith("> ")) {
fieldName = extractFieldName(fieldName, str);
str = skipOtherFieldHeaderLines(str);
String data = extractFieldData(str);
if (fieldName != null) {
logger.info("fieldName, data: ", fieldName, ", ", data);
m.setProperty(fieldName, data);
}
}
currentLine = input.readLine();
}
}
private String extractFieldData(String str) throws IOException {
StringBuilder data = new StringBuilder();
while (str.trim().length() > 0) {
logger.debug("data line: ", currentLine);
data.append(str);
currentLine = input.readLine();
str = new String(currentLine).trim();
}
return data.toString();
}
private String skipOtherFieldHeaderLines(String str) throws IOException {
while (str.startsWith("> ")) {
logger.debug("data header line: ", currentLine);
currentLine = input.readLine();
str = new String(currentLine);
}
return str;
}
private String extractFieldName(String fieldName, String str) {
int index = str.indexOf("<");
if (index != -1) {
int index2 = str.substring(index).indexOf(">");
if (index2 != -1) {
fieldName = str.substring(
index+1,
index+index2
);
}
}
return fieldName;
}
/**
* Returns the next IMolecule.
*/
public IChemObject next() {
if (!nextAvailableIsKnown) {
hasNext();
}
nextAvailableIsKnown = false;
if (!hasNext) {
throw new NoSuchElementException();
}
return nextMolecule;
}
@TestMethod("testClose")
public void close() throws IOException {
input.close();
}
public void remove() {
throw new UnsupportedOperationException();
}
@TestMethod("testSetReader_Reader")
public void setReader(Reader reader) {
if (reader instanceof BufferedReader) {
input = (BufferedReader)reader;
} else {
input = new BufferedReader(reader);
}
nextMolecule = null;
nextAvailableIsKnown = false;
hasNext = false;
}
@TestMethod("testSetReader_InputStream")
public void setReader(InputStream reader) {
setReader(new InputStreamReader(reader));
}
private void initIOSettings() {
forceReadAs3DCoords = new BooleanIOSetting("ForceReadAs3DCoordinates", IOSetting.LOW,
"Should coordinates always be read as 3D?",
"false");
}
public void customizeJob() {
fireIOSettingQuestion(forceReadAs3DCoords);
}
public IOSetting[] getIOSettings() {
IOSetting[] settings = new IOSetting[1];
settings[0] = forceReadAs3DCoords;
return settings;
}
public void processIOSettingQuestion(IOSetting setting) {
if (setting.getName().equals(forceReadAs3DCoords.getName())) {
try {
setting.setSetting(forceReadAs3DCoords.getSetting());
} catch (CDKException e) {
logger.debug("Could not propagate forceReadAs3DCoords setting");
}
}
}
}