File: lightsdf.py

package info (click to toggle)
inchi 1.03%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 12,912 kB
  • sloc: ansic: 102,159; cpp: 7,685; python: 672; makefile: 308; sh: 1
file content (418 lines) | stat: -rw-r--r-- 14,990 bytes parent folder | download | duplicates (2)
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#!/usr/bin/python
#
# International Chemical Identifier (InChI)
# Version 1
# Software version 1.02
# November 30, 2008
# Developed at NIST
# 
# The InChI library and programs are free software developed under the
# auspices of the International Union of Pure and Applied Chemistry (IUPAC);
# you can redistribute this software and/or modify it under the terms of 
# the GNU Lesser General Public License as published by the Free Software 
# Foundation:
# http://www.opensource.org/licenses/lgpl-license.php
# 


#===============================================================
#
# Light SDF reader object (used by InChI generation example)
#
#	Parsing MDL SD file records and collecting information
#	(atomic, bonding, etc.) for further use
#	The implementation is very 'light' and is provided for
#	illustrative purposes only.
#
#
#===============================================================


#---------------------------------------------------------------- 
def sint(s):
        """ smart convert to int """    
        ss = string.strip(s)
        if ss == '':
                return 0
        return int(ss)
#---------------------------------------------------------------- 
def sfloat(s):
        """ smart convert to float """  
        ss = string.strip(s)
        if ss == '':
                return 0.0
        return float(ss)
#---------------------------------------------------------------- 
def stripw(s):
        """ strip common-use whitespaces -
		leading, trailing, and within-string """  
        s1 = string.strip(s)
        s1 = string.replace(s1,'\n','')
        s1 = string.replace(s1,'\r','')
        s1 = string.replace(s1,'\t','')
        return s1
#---------------------------------------------------------------- 
def isstruct(record):
        """ check if structural data present in SDF record
                return 
                1 if structural data present or 
                0 - otherwise """

        if string.count(record['Structure_as_text'],'\n') < 5:
                return 0
        else:
                return 1
#---------------------------------------------------------------- 
def convert_MDL_structure_as_text_to_preobject(text,strname=''):
        """ convert structure in MDL's SDF record 
        	from textual representation to object """

        record = {}
	
        lines = string.split(text,'\n')

	record['Name'] = strname
	if (strname==''):
		name_line = stripw(lines[0])
		if (name_line!=''):
			record['Name'] = name_line

        counts_line = lines[3]

        try:
                natoms = sint(counts_line[:3])
                record['Natoms'] = natoms
        except:
                raise 'MDL_CT_ERROR_COUNTS',natoms
        try:
                nbonds = sint(counts_line[3:6])
                record['Nbonds'] = nbonds
        except:
                raise 'MDL_CT_ERROR_COUNTS',nbonds
        try:
                chiral_flag = sint(counts_line[12:15])
        except:
                raise 'MDL_CT_ERROR_COUNTS', chiral_flag
        try:
                nproplines = sint(counts_line[30:33])
		#print 'nproplines',nproplines
        except:
                raise 'MDL_CT_ERROR_COUNTS', nproplines


        # atom block

        atom_block = lines[4:4+natoms] 
        record['Atoms'] = []
        for line in atom_block:
                try:
                        x = sfloat(line[:10])
                        y = sfloat(line[10:20])
                        z = sfloat(line[20:30])
                        atname = string.strip(line[31:34])
                        dd = sint(line[34:36])
                        charge = sint(line[36:39])      
                        stereo_pairity = sint(line[39:42])
                        hydrogen_count = sint(line[42:45])
                        stereo_care = sint(line[45:48])
                        valence = sint(line[48:51])
                        h0_designator = sint(line[51:54])
                        reac_component_type = sint(line[54:57])
                        reac_component_num = sint(line[57:60])
                        atom_mapping_num = sint(line[60:63])
                        inv_ret_flag = sint(line[63:66])
                        exact_change_flag = sint(line[66:69])
			record['Atoms'].append( (atname, charge, (x,y,z) ,
						 stereo_pairity, 
						 hydrogen_count, 
						 stereo_care, 
						 valence, 
						 h0_designator, 
						 reac_component_type, 
						 reac_component_num, 
						 atom_mapping_num, 
						 inv_ret_flag, 
						 exact_change_flag,
						 dd ) )
                except:
                        raise 'MDL_CT_ERROR_ATOM'
                

        # bond block
        bond_block = lines[4+natoms:4+natoms+nbonds]
        record['Bonds'] = []
        for line in bond_block:
                try:
                        atom1 = sint(line[:3])
                        atom2 = sint(line[3:6])
                        type = sint(line[6:9])
                        stereo = sint(line[9:12])
                        topology = sint(line[15:18])
                        reac_center = sint(line[18:21])
                        record['Bonds'].append( (atom1, atom2, type, stereo, topology, reac_center) )
                except:
                        raise 'MDL_CT_ERROR_BOND'

        # prop block
        # NB: we do not refer to nproplines in counts line
	# instead, check possible property lines directly
        record['Prop'] = []
        for line in lines[4+natoms+nbonds:]:
                try:
			if line[:1]=="M":
				record['Prop'].append(line)
		except:
                        raise 'MDL_PROP_LINE_ERROR'

        return record





#===============================================================

"""
        Base class for light representation/processing of MDL SD file
	Light means no conversion to internal molobject representation,
	just parsing the text and collecting fields
"""

import sys, os, time, string


class SDF_file:
        """
        Base class for representation/processing of MDL's SD file

        SD file is represented as a collection (Python's list)
        of records with associated file name.

        Each record is a Python's dictionary, i.e. a series of
        pairs {key:value}.

        One key is pre-defined: 'Structure_as_text'
        Corresponding value, record['Structure_as_text'],
        contains structure representation as the text just as
        it stands in SDF file.

        All other keys (and values) are established as described
        in SDF file (key is that name which appeared in "> <key> ..."
        strings).       


        """
#---------------------------------------------------------------- 
        def __init__(self):
                """ SDF_file 
                        object constructor """
                
                self.records = []
                self.nrecords = 0
                self.fname = ''         
                self.fp = None
                self.keys = []


#---------------------------------------------------------------- 
        def open(self,fname):
                """ open SD file for reading """

                self.fname = fname

                try:
                        self.fp = open(fname,'rb')
                	self.nrecords = 0
	                self.records = []
                except:
                        return 0
                return 1


#---------------------------------------------------------------- 
        def read(self):
                """ read SDF file content """

                self.nrecords = 0
                self.records = []
                while 1:                
                        rec = self.readnext()
                        if rec == None:
                                break
                        #else:
                                self.nrecords = self.nrecords + 1
                                #print '[%-ld records]\r'%self.nrecords,
                                self.records.append(rec)
				#pass
                self.getkeys()
                #print


#---------------------------------------------------------------- 
        def readnext(self):
                """ read next record in SDF_file """

                rec = {}
                key = 'Structure_as_text'               
                rec[key] = ''

                # read line by line while no $$$$ sign occur

                while 1:

                        line = self.fp.readline()

                        if not line:
                                # EOF reached
                                # NB: last line in SDF should be empty
                                return None

                        if line[:4] == '$$$$' :
                                # have end-of-record line
                                rec[key] = string.rstrip(rec[key]) #remove trailing linefeed
                                break

                        if line[:1] == '>' :
                                # have field-name line
                                # remove trailing linefeed
                                rec[key] = string.rstrip(rec[key]) 
                                # extract field name
                                pos0 = string.find(line[1:],'<')
                                pos = string.find(line[pos0+1:],'>')
                                if pos < 1:
                                        key = 'empty'
                                else:
                                        key = line[pos0+2:pos0+pos+1]
                                rec[key] = ''

                        else:
                                # have field-content line
                                rec[key] = rec[key] + string.rstrip(line)+'\n'


#		if rec != None:
#			self.nrecords = self.nrecords + 1
#                       self.records.append(rec)

                return rec


#---------------------------------------------------------------- 
        def getkeys(self,sort=0):
                """ collect all the field names (keys) 
                        optionally, sort them lexicographically """

                self.keys = []
                for r in self.records:
                        rks = r.keys()
                        for rk in rks:
                                if rk not in self.keys:
                                        self.keys.append(rk)
                if sort>0:
                        self.keys.sort()
		return self.keys


#---------------------------------------------------------------- 
        def exportcsv(self,fwname, numbers=[], fields=[]):
                """ write content of specified fields (non-structural data) 
                        into comma-separated-values (.csv) format file """

                try:
                        fw = open(fwname,'wt')
                except:
                        return 0
                if  numbers == []:
                        numbers = range(self.nrecords)

                if fields == []:
                        fields = self.keys              


                # write field names in 1st line

                s = ''
                for k in fields:
                        
                        if k!='Structure_as_text':      # skip structure field
                                sk = k
                                if ' ' in sk:
                                        if '"' in sk:
                                                sk = string.replace(sk,'"','\'\'')
                                        s = s + '"' + sk + '",'
                                else:
                                        s = s + sk + ','
                fw.write('%-s\n'%s[:-1])

                # for each record write the fields

                for i in numbers:
                        r = self.records[i]
                        s = ''
                        for k in fields:
                                if k!='Structure_as_text':
                                        try:
                                                val = r[k]
                                                val = stripw(val)
                                        except:
                                                val = ''
                                        if ' ' in val or ',' in val:
                                                if '"' in val:
                                                        val = string.replace(val,'"','\'\'')
                                                s = s + '"' + val + '",'
                                        else:
                                                s = s + val + ','

                        fw.write('%-s\n'%s[:-1])

                return 1


#---------------------------------------------------------------- 
        def write(self,fwname,numbers=[]):
                """ write SDF file containing specified 
                        records  in specified order """

                try:
                        fw = open(fwname,'wt')
                except:
                        return 0
                if numbers == []:
                        numbers = range(self.nrecords)
                for i in numbers:
                        r = self.records[i]
                        #place structure at first
                        fw.write('%-s\n'%r['Structure_as_text'])
                        for k in r.keys():
                                if k!='Structure_as_text':
                                        fw.write('>  <%-s>\n'%k)
                                        fw.write('%-s\n\n'%r[k])
                        fw.write('$$$$\n')
                return 1


#---------------------------------------------------------------- 
        def getfieldduplicates(self,field):
                """ get duplicates by field idfield"""

                dup = {}
                ilist = range(self.nrecords) #all internal nos
                for i in ilist:
                        m = self.records[i]
                        try:
                                f = m[field]
                        except:
                                # no such field in this record
                                continue
                        try:
                                #if this id still here, add item
                                dup[f] = dup[f] + [i] 
                        except:
                                #if no this id presents, create entry
                                dup[f] = [i] 
                for dk in dup.keys():
                        if len(dup[dk])<2:
                                del dup[dk]
                return dup