text
stringlengths
0
1.05M
meta
dict
import os import io import sys import unittest from rdkit import RDConfig #import pickle from rdkit.six.moves import cPickle as pickle from rdkit import DataStructs as ds class TestCase(unittest.TestCase): def setUp(self): pass def test1Discrete(self): v1 = ds.DiscreteValueVect(ds.DiscreteValueType.ONEBITVALUE, 30) for i in range(15): v1[2 * i] = 1 self.assertTrue(len(v1) == 30) self.assertTrue(v1.GetTotalVal() == 15) for i in range(len(v1)): self.assertTrue(v1[i] == (i + 1) % 2) self.assertRaises(ValueError, lambda: v1.__setitem__(5, 2)) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 30) for i in range(len(v1)): v1[i] = i % 4 self.assertTrue(len(v1) == 30) for i in range(len(v1)): self.assertTrue(v1[i] == i % 4) self.assertRaises(ValueError, lambda: v1.__setitem__(10, 6)) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 30) for i in range(len(v1)): v1[i] = i % 16 self.assertTrue(len(v1) == 30) self.assertTrue(v1.GetTotalVal() == 211) for i in range(len(v1)): self.assertTrue(v1[i] == i % 16) self.assertRaises(ValueError, lambda: v1.__setitem__(10, 16)) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.EIGHTBITVALUE, 32) for i in range(len(v1)): v1[i] = i % 256 self.assertTrue(len(v1) == 32) self.assertTrue(v1.GetTotalVal() == 496) for i in range(len(v1)): self.assertTrue(v1[i] == i % 256) self.assertRaises(ValueError, lambda: v1.__setitem__(10, 256)) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.SIXTEENBITVALUE, 300) for i in range(len(v1)): v1[i] = i % 300 self.assertTrue(len(v1) == 300) self.assertTrue(v1.GetTotalVal() == 44850) self.assertRaises(ValueError, lambda: v1.__setitem__(10, 65536)) def test2VectDistances(self): v1 = ds.DiscreteValueVect(ds.DiscreteValueType.ONEBITVALUE, 30) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.ONEBITVALUE, 30) for i in range(15): v1[2 * i] = 1 v2[2 * i] = 1 self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) for i in range(30): if (i % 3 == 0): v2[i] = 1 else: v2[i] = 0 self.assertTrue(ds.ComputeL1Norm(v1, v2) == 15) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 30) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 30) for i in range(30): v1[i] = i % 4 v2[i] = (i + 1) % 4 self.assertTrue(ds.ComputeL1Norm(v1, v2) == 44) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 16) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 16) for i in range(16): v1[i] = i % 16 v2[i] = i % 5 self.assertTrue(ds.ComputeL1Norm(v1, v2) == 90) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.EIGHTBITVALUE, 5) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.EIGHTBITVALUE, 5) v1[0] = 34 v1[1] = 167 v1[2] = 3 v1[3] = 56 v1[4] = 128 v2[0] = 14 v2[1] = 67 v2[2] = 103 v2[3] = 6 v2[4] = 228 self.assertTrue(ds.ComputeL1Norm(v1, v2) == 370) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.SIXTEENBITVALUE, 3) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.SIXTEENBITVALUE, 3) v1[0] = 2345 v1[1] = 64578 v1[2] = 34 v2[0] = 1345 v2[1] = 54578 v2[2] = 10034 self.assertTrue(ds.ComputeL1Norm(v1, v2) == 21000) def test3Pickles(self): #outF = file('dvvs.pkl','wb+') with open(os.path.join(RDConfig.RDBaseDir, 'Code/DataStructs/Wrap/testData/dvvs.pkl'), 'r') as inTF: buf = inTF.read().replace('\r\n', '\n').encode('utf-8') inTF.close() with io.BytesIO(buf) as inF: v1 = ds.DiscreteValueVect(ds.DiscreteValueType.ONEBITVALUE, 30) for i in range(15): v1[2 * i] = 1 v2 = pickle.loads(pickle.dumps(v1)) self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) #cPickle.dump(v1,outF) v2 = pickle.load(inF, encoding='bytes') self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) self.assertTrue(v1.GetTotalVal() == v2.GetTotalVal()) self.assertTrue(v2.GetTotalVal() != 0) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 30) for i in range(30): v1[i] = i % 4 v2 = pickle.loads(pickle.dumps(v1)) self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) #pickle.dump(v1,outF) v2 = pickle.load(inF, encoding='bytes') self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) self.assertTrue(v1.GetTotalVal() == v2.GetTotalVal()) self.assertTrue(v2.GetTotalVal() != 0) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 16) for i in range(16): v1[i] = i % 16 v2 = pickle.loads(pickle.dumps(v1)) self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) #pickle.dump(v1,outF) v2 = pickle.load(inF, encoding='bytes') self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) self.assertTrue(v1.GetTotalVal() == v2.GetTotalVal()) self.assertTrue(v2.GetTotalVal() != 0) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.EIGHTBITVALUE, 5) v1[0] = 34 v1[1] = 167 v1[2] = 3 v1[3] = 56 v1[4] = 128 v2 = pickle.loads(pickle.dumps(v1)) self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) #pickle.dump(v1,outF) v2 = pickle.load(inF, encoding='bytes') self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) self.assertTrue(v1.GetTotalVal() == v2.GetTotalVal()) self.assertTrue(v2.GetTotalVal() != 0) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.SIXTEENBITVALUE, 3) v1[0] = 2345 v1[1] = 64578 v1[2] = 34 v2 = pickle.loads(pickle.dumps(v1)) self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) #pickle.dump(v1,outF) v2 = pickle.load(inF, encoding='bytes') self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) self.assertTrue(v1.GetTotalVal() == v2.GetTotalVal()) self.assertTrue(v2.GetTotalVal() != 0) def test4DiscreteVectOps(self): v1 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 8) for i in range(4): v1[2 * i] = 2 self.assertTrue(v1.GetTotalVal() == 8) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 8) for i in range(4): v2[2 * i + 1] = 2 v2[2 * i] = 1 self.assertTrue(v2.GetTotalVal() == 12) v3 = v1 | v2 self.assertTrue(len(v3) == len(v2)) self.assertTrue(v3.GetTotalVal() == 16) v3 = v1 & v2 self.assertTrue(len(v3) == len(v2)) self.assertTrue(v3.GetTotalVal() == 4) v4 = v1 + v2 self.assertTrue(len(v4) == len(v2)) self.assertTrue(v4.GetTotalVal() == 20) v4 = v1 - v2 self.assertTrue(v4.GetTotalVal() == 4) v4 = v2 - v1 self.assertTrue(v4.GetTotalVal() == 8) v4 = v2 v4 -= v1 self.assertTrue(v4.GetTotalVal() == 8) v4 -= v4 self.assertTrue(v4.GetTotalVal() == 0) def testIterator(self): """ connected to sf.net issue 1719831: http://sourceforge.net/tracker/index.php?func=detail&aid=1719831&group_id=160139&atid=814650 """ v1 = ds.DiscreteValueVect(ds.DiscreteValueType.ONEBITVALUE, 30) for i in range(15): v1[2 * i] = 1 l1 = list(v1) self.assertTrue(len(l1) == len(v1)) for i, v in enumerate(v1): self.assertTrue(l1[i] == v) self.assertRaises(IndexError, lambda: v1[40]) def test9ToNumpy(self): import numpy bv = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 32) bv[0] = 1 bv[1] = 4 bv[17] = 1 bv[23] = 8 bv[31] = 12 arr = numpy.zeros((3, ), 'i') ds.ConvertToNumpyArray(bv, arr) for i in range(len(bv)): self.assertEqual(bv[i], arr[i]) if __name__ == '__main__': unittest.main()
{ "repo_name": "jandom/rdkit", "path": "Code/DataStructs/Wrap/testDiscreteValueVect.py", "copies": "5", "size": "7843", "license": "bsd-3-clause", "hash": 5598968770083604000, "line_mean": 29.0498084291, "line_max": 96, "alpha_frac": 0.6155807727, "autogenerated": false, "ratio": 2.67679180887372, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5792372581573719, "avg_score": null, "num_lines": null }
import os, sys import io import unittest from rdkit.six.moves import cPickle from rdkit import RDConfig from rdkit import DataStructs as ds def feq(v1, v2, tol=1e-4): return abs(v1 - v2) < tol class TestCase(unittest.TestCase): def setUp(self): pass def test1Int(self): """ """ v1 = ds.IntSparseIntVect(5) self.assertRaises(IndexError, lambda: v1[5]) v1[0] = 1 v1[2] = 2 v1[3] = 3 self.assertTrue(v1 == v1) self.assertTrue(v1.GetLength() == 5) v2 = ds.IntSparseIntVect(5) self.assertTrue(v1 != v2) v2 |= v1 self.assertTrue(v2 == v1) v3 = v2 | v1 self.assertTrue(v3 == v1) onVs = v1.GetNonzeroElements() self.assertTrue(onVs == {0: 1, 2: 2, 3: 3}) def test2Long(self): """ """ l = 1 << 42 v1 = ds.LongSparseIntVect(l) self.assertRaises(IndexError, lambda: v1[l]) v1[0] = 1 v1[2] = 2 v1[1 << 35] = 3 self.assertTrue(v1 == v1) self.assertTrue(v1.GetLength() == l) v2 = ds.LongSparseIntVect(l) self.assertTrue(v1 != v2) v2 |= v1 self.assertTrue(v2 == v1) v3 = v2 | v1 self.assertTrue(v3 == v1) onVs = v1.GetNonzeroElements() self.assertTrue(onVs == {0: 1, 2: 2, 1 << 35: 3}) def test3Pickle1(self): """ """ l = 1 << 42 v1 = ds.LongSparseIntVect(l) self.assertRaises(IndexError, lambda: v1[l + 1]) v1[0] = 1 v1[2] = 2 v1[1 << 35] = 3 self.assertTrue(v1 == v1) v2 = cPickle.loads(cPickle.dumps(v1)) self.assertTrue(v2 == v1) v3 = ds.LongSparseIntVect(v2.ToBinary()) self.assertTrue(v2 == v3) self.assertTrue(v1 == v3) #cPickle.dump(v1,file('lsiv.pkl','wb+')) with open(os.path.join(RDConfig.RDBaseDir, 'Code/DataStructs/Wrap/testData/lsiv.pkl'), 'r') as tf: buf = tf.read().replace('\r\n', '\n').encode('utf-8') tf.close() with io.BytesIO(buf) as f: v3 = cPickle.load(f) self.assertTrue(v3 == v1) def test3Pickle2(self): """ """ l = 1 << 21 v1 = ds.IntSparseIntVect(l) self.assertRaises(IndexError, lambda: v1[l + 1]) v1[0] = 1 v1[2] = 2 v1[1 << 12] = 3 self.assertTrue(v1 == v1) v2 = cPickle.loads(cPickle.dumps(v1)) self.assertTrue(v2 == v1) v3 = ds.IntSparseIntVect(v2.ToBinary()) self.assertTrue(v2 == v3) self.assertTrue(v1 == v3) #cPickle.dump(v1,file('isiv.pkl','wb+')) with open(os.path.join(RDConfig.RDBaseDir, 'Code/DataStructs/Wrap/testData/isiv.pkl'), 'r') as tf: buf = tf.read().replace('\r\n', '\n').encode('utf-8') tf.close() with io.BytesIO(buf) as f: v3 = cPickle.load(f) self.assertTrue(v3 == v1) def test4Update(self): """ """ v1 = ds.IntSparseIntVect(5) self.assertRaises(IndexError, lambda: v1[6]) v1[0] = 1 v1[2] = 2 v1[3] = 3 self.assertTrue(v1 == v1) v2 = ds.IntSparseIntVect(5) v2.UpdateFromSequence((0, 2, 3, 3, 2, 3)) self.assertTrue(v1 == v2) def test5Dice(self): """ """ v1 = ds.IntSparseIntVect(5) v1[4] = 4 v1[0] = 2 v1[3] = 1 self.assertTrue(feq(ds.DiceSimilarity(v1, v1), 1.0)) v1 = ds.IntSparseIntVect(5) v1[0] = 2 v1[2] = 1 v1[3] = 4 v1[4] = 6 v2 = ds.IntSparseIntVect(5) v2[1] = 2 v2[2] = 3 v2[3] = 4 v2[4] = 4 self.assertTrue(feq(ds.DiceSimilarity(v1, v2), 18.0 / 26.)) self.assertTrue(feq(ds.DiceSimilarity(v2, v1), 18.0 / 26.)) def test6BulkDice(self): """ """ sz = 10 nToSet = 5 nVs = 6 import random vs = [] for i in range(nVs): v = ds.IntSparseIntVect(sz) for j in range(nToSet): v[random.randint(0, sz - 1)] = random.randint(1, 10) vs.append(v) baseDs = [ds.DiceSimilarity(vs[0], vs[x]) for x in range(1, nVs)] bulkDs = ds.BulkDiceSimilarity(vs[0], vs[1:]) for i in range(len(baseDs)): self.assertTrue(feq(baseDs[i], bulkDs[i])) def test6BulkTversky(self): """ """ sz = 10 nToSet = 5 nVs = 6 import random vs = [] for i in range(nVs): v = ds.IntSparseIntVect(sz) for j in range(nToSet): v[random.randint(0, sz - 1)] = random.randint(1, 10) vs.append(v) baseDs = [ds.TverskySimilarity(vs[0], vs[x], .5, .5) for x in range(1, nVs)] bulkDs = ds.BulkTverskySimilarity(vs[0], vs[1:], 0.5, 0.5) diceDs = [ds.DiceSimilarity(vs[0], vs[x]) for x in range(1, nVs)] for i in range(len(baseDs)): self.assertTrue(feq(baseDs[i], bulkDs[i])) self.assertTrue(feq(baseDs[i], diceDs[i])) bulkDs = ds.BulkTverskySimilarity(vs[0], vs[1:], 1.0, 1.0) taniDs = [ds.TanimotoSimilarity(vs[0], vs[x]) for x in range(1, nVs)] for i in range(len(bulkDs)): self.assertTrue(feq(bulkDs[i], taniDs[i])) taniDs = ds.BulkTanimotoSimilarity(vs[0], vs[1:]) for i in range(len(bulkDs)): self.assertTrue(feq(bulkDs[i], taniDs[i])) if __name__ == '__main__': unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "Code/DataStructs/Wrap/testSparseIntVect.py", "copies": "5", "size": "5086", "license": "bsd-3-clause", "hash": -1196875555295780900, "line_mean": 22.4377880184, "line_max": 90, "alpha_frac": 0.5674400315, "autogenerated": false, "ratio": 2.589613034623218, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006529444162840771, "num_lines": 217 }
import os,sys import unittest from rdkit.six.moves import cPickle from rdkit import RDConfig from rdkit import DataStructs as ds def feq(v1,v2,tol=1e-4): return abs(v1-v2)<tol class TestCase(unittest.TestCase): def setUp(self) : pass def test1Int(self): """ """ v1 = ds.IntSparseIntVect(5) self.assertRaises(IndexError,lambda:v1[5]) v1[0]=1 v1[2]=2 v1[3]=3 self.assertTrue(v1==v1) self.assertTrue(v1.GetLength()==5) v2= ds.IntSparseIntVect(5) self.assertTrue(v1!=v2) v2|=v1 self.assertTrue(v2==v1) v3=v2|v1 self.assertTrue(v3==v1) onVs = v1.GetNonzeroElements() self.assertTrue(onVs=={0:1,2:2,3:3}) def test2Long(self): """ """ l=1<<42 v1 = ds.LongSparseIntVect(l) self.assertRaises(IndexError,lambda:v1[l]) v1[0]=1 v1[2]=2 v1[1<<35]=3 self.assertTrue(v1==v1) self.assertTrue(v1.GetLength()==l) v2= ds.LongSparseIntVect(l) self.assertTrue(v1!=v2) v2|=v1 self.assertTrue(v2==v1) v3=v2|v1 self.assertTrue(v3==v1) onVs = v1.GetNonzeroElements() self.assertTrue(onVs=={0:1,2:2,1<<35:3}) def test3Pickle1(self): """ """ l=1<<42 v1 = ds.LongSparseIntVect(l) self.assertRaises(IndexError,lambda:v1[l+1]) v1[0]=1 v1[2]=2 v1[1<<35]=3 self.assertTrue(v1==v1) v2= cPickle.loads(cPickle.dumps(v1)) self.assertTrue(v2==v1) v3= ds.LongSparseIntVect(v2.ToBinary()) self.assertTrue(v2==v3) self.assertTrue(v1==v3) #cPickle.dump(v1,file('lsiv.pkl','wb+')) with open( os.path.join(RDConfig.RDBaseDir, 'Code/DataStructs/Wrap/testData/lsiv.pkl'), 'rb' ) as f: v3 = cPickle.load(f) self.assertTrue(v3==v1) def test3Pickle2(self): """ """ l=1<<21 v1 = ds.IntSparseIntVect(l) self.assertRaises(IndexError,lambda:v1[l+1]) v1[0]=1 v1[2]=2 v1[1<<12]=3 self.assertTrue(v1==v1) v2= cPickle.loads(cPickle.dumps(v1)) self.assertTrue(v2==v1) v3= ds.IntSparseIntVect(v2.ToBinary()) self.assertTrue(v2==v3) self.assertTrue(v1==v3) #cPickle.dump(v1,file('isiv.pkl','wb+')) with open( os.path.join(RDConfig.RDBaseDir, 'Code/DataStructs/Wrap/testData/isiv.pkl'), 'rb' ) as f: v3 = cPickle.load(f) self.assertTrue(v3==v1) def test4Update(self): """ """ v1 = ds.IntSparseIntVect(5) self.assertRaises(IndexError,lambda:v1[6]) v1[0]=1 v1[2]=2 v1[3]=3 self.assertTrue(v1==v1) v2 = ds.IntSparseIntVect(5) v2.UpdateFromSequence((0,2,3,3,2,3)) self.assertTrue(v1==v2) def test5Dice(self): """ """ v1 = ds.IntSparseIntVect(5) v1[4]=4; v1[0]=2; v1[3]=1; self.assertTrue(feq(ds.DiceSimilarity(v1,v1),1.0)) v1 = ds.IntSparseIntVect(5) v1[0]=2; v1[2]=1; v1[3]=4; v1[4]=6; v2 = ds.IntSparseIntVect(5) v2[1]=2; v2[2]=3; v2[3]=4; v2[4]=4; self.assertTrue(feq(ds.DiceSimilarity(v1,v2),18.0/26.)) self.assertTrue(feq(ds.DiceSimilarity(v2,v1),18.0/26.)) def test6BulkDice(self): """ """ sz=10 nToSet=5 nVs=6 import random vs = [] for i in range(nVs): v = ds.IntSparseIntVect(sz) for j in range(nToSet): v[random.randint(0,sz-1)]=random.randint(1,10) vs.append(v) baseDs = [ds.DiceSimilarity(vs[0],vs[x]) for x in range(1,nVs)] bulkDs = ds.BulkDiceSimilarity(vs[0],vs[1:]) for i in range(len(baseDs)): self.assertTrue(feq(baseDs[i],bulkDs[i])) def test6BulkTversky(self): """ """ sz=10 nToSet=5 nVs=6 import random vs = [] for i in range(nVs): v = ds.IntSparseIntVect(sz) for j in range(nToSet): v[random.randint(0,sz-1)]=random.randint(1,10) vs.append(v) baseDs = [ds.TverskySimilarity(vs[0],vs[x],.5,.5) for x in range(1,nVs)] bulkDs = ds.BulkTverskySimilarity(vs[0],vs[1:],0.5,0.5) diceDs = [ds.DiceSimilarity(vs[0],vs[x]) for x in range(1,nVs)] for i in range(len(baseDs)): self.assertTrue(feq(baseDs[i],bulkDs[i])) self.assertTrue(feq(baseDs[i],diceDs[i])) bulkDs = ds.BulkTverskySimilarity(vs[0],vs[1:],1.0,1.0) taniDs = [ds.TanimotoSimilarity(vs[0],vs[x]) for x in range(1,nVs)] for i in range(len(bulkDs)): self.assertTrue(feq(bulkDs[i],taniDs[i])) taniDs = ds.BulkTanimotoSimilarity(vs[0],vs[1:]) for i in range(len(bulkDs)): self.assertTrue(feq(bulkDs[i],taniDs[i])) if __name__ == '__main__': unittest.main()
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "Code/DataStructs/Wrap/testSparseIntVect.py", "copies": "1", "size": "4724", "license": "bsd-3-clause", "hash": -2648055240601702400, "line_mean": 21.1784037559, "line_max": 76, "alpha_frac": 0.5859441152, "autogenerated": false, "ratio": 2.51009564293305, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.359603975813305, "avg_score": null, "num_lines": null }
""" A selection of useful transforms for the chainable transform layer. Each method is a closure that must return a transform method, the instance of the transform. Each returned method takes two arguments, the data to transform and a dictionary of additional data, and output a single value, the transformed data. Optionally static arguments may be passed in after the input data argument to control the transform """ import sys import os import types from peloton.utils import logging from peloton.utils.simplexml import HTMLFormatter from peloton.utils.simplexml import XMLFormatter from peloton.exceptions import PelotonError def valueToDict(conf={}): """ Takes data and returns the dict {'d':data}. """ def _fn(data, opts={}): return {'d':data, '_sys':opts} return _fn def stripKeys(conf, *args): """ Data must be a dict; each arg is taken as a key which, if it exists in data, is removed. """ def _fn(data, opts): if not type(data) == types.DictType: return for k in args: if data.has_key(k): del(data[k]) return data return _fn def upperKeys(conf={}): """ A rather pointless transform, largely for testing purposes. Transforms all keys in data (assuming it is a dictionary) to uppercase. """ def _fn(data, opts): if not type(data) == types.DictType: return for k,v in data.items(): if type(k) == types.StringType: data[k.upper()] = v del(data[k]) return data return _fn def string(conf={}): """ Stringify output """ def _fn(data, opts): return str(data) return _fn xmlFormatter = XMLFormatter() htmlFormatter = HTMLFormatter() def defaultXMLTransform(conf={}): def _fn(data, opts): return xmlFormatter.format(data) return _fn def defaultHTMLTransform(conf={}): def _fn(data, opts): return htmlFormatter.format(data) return _fn import simplejson class JSONFormatter(object): def format(self,v): """ Returns content-type, content. """ try: s = simplejson.dumps(v) except: s = u'"Unserialisable response: %s"' % str(v) return s jsonFormatter = JSONFormatter() def jsonTransform(conf={}): def _fn(data, opts): return jsonFormatter.format(data) return _fn from genshi.template import TemplateLoader templateLoader = TemplateLoader([]) templateLoader.auto_reload = True try: from django.template import Template, Context import django.template.loader os.environ["DJANGO_SETTINGS_MODULE"] = "__main__" from django.conf import settings settings.TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) # list not tupple so that it can be appended to settings.TEMPLATE_DIRS = [] DJANGO_ENABLED = True except: DJANGO_ENABLED = False def _expand(conf, f): """ If f is ~ return the full path to it. If $NAME is found, substitute for the published name of the service.""" if f and f == '~': return conf['resourceRoot'] elif f and f.find('@NAME') > -1: return f.replace('@NAME', conf['publishedName']) else: return f def template(conf, templateFile): """ Passes data through a template. Automaticaly applies valueToDict if the data is not a dictionary. template file is either an absolute path (not recommended practice) or relative to the resource folder of the service. The former always starts '/', the latter always '~/' for absolute clarity. Thus template foo.html.genshi may be referenced as:: ~/templates/DuckPond/foo.html.genshi If the path contains the published name of the service, this may be written as @NAME and will be substituted at runtime. Thus:: ~/templates/@NAME/foo.html.genshi will translate, when run in a service published as AirforceOne, to:: ~/templates/AirforceOne/foo.html.genshi Genshi is not the only fruit; if the Django libraries are on the python path you may also use Django templating. A Django template is indicated by the suffix '.django', e.g:: ~/templates/AirforceOne/foo.html.django """ _valueToDict = valueToDict() # expand any ~ entries path, file = os.path.split(templateFile) try: path = [_expand(conf, i) for i in path.split('/')] except: path=[] path = os.path.abspath("/".join(path)) templateFile = "%s/%s" % (path, file) if DJANGO_ENABLED and path not in settings.TEMPLATE_DIRS: settings.TEMPLATE_DIRS.append(path) def _fn(data, opts): if not type(data) == types.DictType: data = _valueToDict(data) data['_sys'] = opts data['_sys']['templateFile'] = templateFile if templateFile[-6:] == 'django': if not DJANGO_ENABLED: raise PelotonError("DJANGO templates not supported: Django libraries not in path") fp = open(templateFile) template = Template(fp.read()) fp.close() context = Context(data) return template.render(context) else: template = templateLoader.load(templateFile) return template.generate(**data).render() return _fn
{ "repo_name": "aquamatt/Peloton", "path": "src/peloton/utils/transforms.py", "copies": "1", "size": "5530", "license": "bsd-3-clause", "hash": -3097729489654668300, "line_mean": 30.6057142857, "line_max": 98, "alpha_frac": 0.6566003617, "autogenerated": false, "ratio": 3.897110641296688, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5053711002996688, "avg_score": null, "num_lines": null }
import sqlalchemy from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem import Lipinski,Descriptors,Crippen from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbModule import os from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Table,Column,MetaData from sqlalchemy import Integer,Text,String,ForeignKey,Binary,DateTime,Float from sqlalchemy.orm import relation,mapper,sessionmaker,backref from sqlalchemy import create_engine decBase = declarative_base() class Compound(decBase): __tablename__='molecules' guid=Column(Integer,primary_key=True) molpkl=Column(Binary) def RegisterSchema(dbUrl,echo=False): engine = create_engine(dbUrl,echo=echo) decBase.metadata.create_all(engine) maker = sessionmaker(bind=engine) return maker ConnectToSchema=RegisterSchema def _ConnectToSchema(dbUrl,echo=False): engine = create_engine(dbUrl,echo=echo) meta decBase.metadata.create_all(engine) maker = sessionmaker(bind=engine) return maker #set up the logger: import rdkit.RDLogger as logging logger = logging.logger() logger.setLevel(logging.INFO) def ProcessMol(session,mol,globalProps,nDone,nameProp='_Name',nameCol='compound_id', redraw=False,keepHs=False, skipProps=False,addComputedProps=False, skipSmiles=False): if not mol: raise ValueError('no molecule') if keepHs: Chem.SanitizeMol(mol) try: nm = mol.GetProp(nameProp) except KeyError: nm = None if not nm: nm = 'Mol_%d'%nDone cmpd = Compound() session.add(cmpd) if redraw: AllChem.Compute2DCoords(m) if not skipSmiles: cmpd.smiles=Chem.MolToSmiles(mol,True) cmpd.molpkl=mol.ToBinary() setattr(cmpd,nameCol,nm) if not skipProps: if addComputedProps: cmpd.DonorCount=Lipinski.NumHDonors(mol) cmpd.AcceptorCount=Lipinski.NumHAcceptors(mol) cmpd.RotatableBondCount=Lipinski.NumRotatableBonds(mol) cmpd.AMW=Descriptors.MolWt(mol) cmpd.MolLogP=Crippen.MolLogP(mol) pns = list(mol.GetPropNames()) for pi,pn in enumerate(pns): if pn.lower()==nameCol.lower(): continue pv = mol.GetProp(pn).strip() if pn in globalProps: setattr(cmpd,pn.lower(),pv) return cmpd def LoadDb(suppl,dbName,nameProp='_Name',nameCol='compound_id',silent=False, redraw=False,errorsTo=None,keepHs=False,defaultVal='N/A',skipProps=False, regName='molecules',skipSmiles=False,maxRowsCached=-1, uniqNames=False,addComputedProps=False,lazySupplier=False, numForPropScan=10,startAnew=True): if not lazySupplier: nMols = len(suppl) else: nMols=-1 if not silent: logger.info("Generating molecular database in file %s"%dbName) if not lazySupplier: logger.info(" Processing %d molecules"%nMols) globalProps = {} if startAnew: if os.path.exists(dbName): os.unlink(dbName) sIter=iter(suppl) setattr(Compound,nameCol.lower(),Column(nameCol.lower(),String,default=defaultVal,unique=uniqNames)) if not skipSmiles: Compound.smiles = Column(Text,unique=True) if not skipProps: while numForPropScan>0: try: m = next(sIter) except StopIteration: numForPropScan=0 break if not m: continue for pn in m.GetPropNames(): if pn.lower()==nameCol.lower(): continue if pn not in globalProps: globalProps[pn]=1 setattr(Compound,pn.lower(),Column(pn.lower(),String,default=defaultVal)) numForPropScan-=1 if addComputedProps: Compound.DonorCount=Column(Integer) Compound.AcceptorCount=Column(Integer) Compound.RotatableBondCount=Column(Integer) Compound.AMW=Column(Float) Compound.MolLogP=Column(Float) session=RegisterSchema('sqlite:///%s'%(dbName))() nDone = 0 cache=[] for m in suppl: nDone +=1 if not m: if errorsTo: if hasattr(suppl,'GetItemText'): d = suppl.GetItemText(nDone-1) errorsTo.write(d) else: logger.warning('full error file support not complete') continue cmpd=ProcessMol(session,m,globalProps,nDone,nameProp=nameProp, nameCol=nameCol,redraw=redraw, keepHs=keepHs,skipProps=skipProps, addComputedProps=addComputedProps,skipSmiles=skipSmiles) if cmpd is not None: cache.append(cmpd) if not silent and not nDone%100: logger.info(' done %d'%nDone) try: session.commit() except: session.rollback() for cmpd in cache: try: session.add(cmpd) session.commit() except: session.rollback() cache=[] try: session.commit() except: import traceback traceback.print_exc() session.rollback() for cmpd in cache: try: session.add(cmpd) session.commit() except: session.rollback() if __name__=='__main__': import sys sdf =Chem.SDMolSupplier(sys.argv[1]) db =sys.argv[2] LoadDb(sdf,db,addComputedProps=False) session = RegisterSchema('sqlite:///%s'%(db))() print('>>>>', len(session.query(Compound).all()))
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/MolDb/Loader_sa.py", "copies": "3", "size": "5498", "license": "bsd-3-clause", "hash": -2772300596500422000, "line_mean": 27.6354166667, "line_max": 102, "alpha_frac": 0.6740632957, "autogenerated": false, "ratio": 3.320048309178744, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5494111604878744, "avg_score": null, "num_lines": null }
import sqlalchemy from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem import Lipinski, Descriptors, Crippen from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbModule import os from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Table, Column, MetaData from sqlalchemy import Integer, Text, String, ForeignKey, Binary, DateTime, Float from sqlalchemy.orm import relation, mapper, sessionmaker, backref from sqlalchemy import create_engine decBase = declarative_base() class Compound(decBase): __tablename__ = 'molecules' guid = Column(Integer, primary_key=True) molpkl = Column(Binary) def RegisterSchema(dbUrl, echo=False): engine = create_engine(dbUrl, echo=echo) decBase.metadata.create_all(engine) maker = sessionmaker(bind=engine) return maker ConnectToSchema = RegisterSchema def _ConnectToSchema(dbUrl, echo=False): engine = create_engine(dbUrl, echo=echo) meta decBase.metadata.create_all(engine) maker = sessionmaker(bind=engine) return maker #set up the logger: import rdkit.RDLogger as logging logger = logging.logger() logger.setLevel(logging.INFO) def ProcessMol(session, mol, globalProps, nDone, nameProp='_Name', nameCol='compound_id', redraw=False, keepHs=False, skipProps=False, addComputedProps=False, skipSmiles=False): if not mol: raise ValueError('no molecule') if keepHs: Chem.SanitizeMol(mol) try: nm = mol.GetProp(nameProp) except KeyError: nm = None if not nm: nm = 'Mol_%d' % nDone cmpd = Compound() session.add(cmpd) if redraw: AllChem.Compute2DCoords(m) if not skipSmiles: cmpd.smiles = Chem.MolToSmiles(mol, True) cmpd.molpkl = mol.ToBinary() setattr(cmpd, nameCol, nm) if not skipProps: if addComputedProps: cmpd.DonorCount = Lipinski.NumHDonors(mol) cmpd.AcceptorCount = Lipinski.NumHAcceptors(mol) cmpd.RotatableBondCount = Lipinski.NumRotatableBonds(mol) cmpd.AMW = Descriptors.MolWt(mol) cmpd.MolLogP = Crippen.MolLogP(mol) pns = list(mol.GetPropNames()) for pi, pn in enumerate(pns): if pn.lower() == nameCol.lower(): continue pv = mol.GetProp(pn).strip() if pn in globalProps: setattr(cmpd, pn.lower(), pv) return cmpd def LoadDb(suppl, dbName, nameProp='_Name', nameCol='compound_id', silent=False, redraw=False, errorsTo=None, keepHs=False, defaultVal='N/A', skipProps=False, regName='molecules', skipSmiles=False, maxRowsCached=-1, uniqNames=False, addComputedProps=False, lazySupplier=False, numForPropScan=10, startAnew=True): if not lazySupplier: nMols = len(suppl) else: nMols = -1 if not silent: logger.info("Generating molecular database in file %s" % dbName) if not lazySupplier: logger.info(" Processing %d molecules" % nMols) globalProps = {} if startAnew: if os.path.exists(dbName): for i in range(5): try: os.unlink(dbName) break except: import time time.sleep(2) if os.path.exists(dbName): raise IOError('could not delete old database %s' % dbName) sIter = iter(suppl) setattr(Compound, nameCol.lower(), Column(nameCol.lower(), String, default=defaultVal, unique=uniqNames)) if not skipSmiles: Compound.smiles = Column(Text, unique=True) if not skipProps: while numForPropScan > 0: try: m = next(sIter) except StopIteration: numForPropScan = 0 break if not m: continue for pn in m.GetPropNames(): if pn.lower() == nameCol.lower(): continue if pn not in globalProps: globalProps[pn] = 1 setattr(Compound, pn.lower(), Column(pn.lower(), String, default=defaultVal)) numForPropScan -= 1 if addComputedProps: Compound.DonorCount = Column(Integer) Compound.AcceptorCount = Column(Integer) Compound.RotatableBondCount = Column(Integer) Compound.AMW = Column(Float) Compound.MolLogP = Column(Float) session = RegisterSchema('sqlite:///%s' % (dbName))() nDone = 0 cache = [] for m in suppl: nDone += 1 if not m: if errorsTo: if hasattr(suppl, 'GetItemText'): d = suppl.GetItemText(nDone - 1) errorsTo.write(d) else: logger.warning('full error file support not complete') continue cmpd = ProcessMol(session, m, globalProps, nDone, nameProp=nameProp, nameCol=nameCol, redraw=redraw, keepHs=keepHs, skipProps=skipProps, addComputedProps=addComputedProps, skipSmiles=skipSmiles) if cmpd is not None: cache.append(cmpd) if not silent and not nDone % 100: logger.info(' done %d' % nDone) try: session.commit() except Exception: session.rollback() for cmpd in cache: try: session.add(cmpd) session.commit() except Exception: session.rollback() except BaseException: # Rollback even with KeyboardInterrupt session.rollback() raise cache = [] try: session.commit() except BaseException as exc: import traceback traceback.print_exc() session.rollback() for cmpd in cache: try: session.add(cmpd) session.commit() except Exception: session.rollback() except BaseException: session.rollback() raise if not isinstance(exc, Exception): # Re-raise on KeyboardInterrupt, SystemExit, etc. raise exc if __name__ == '__main__': import sys sdf = Chem.SDMolSupplier(sys.argv[1]) db = sys.argv[2] LoadDb(sdf, db, addComputedProps=False) session = RegisterSchema('sqlite:///%s' % (db))() print('>>>>', len(session.query(Compound).all()))
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/MolDb/Loader_sa.py", "copies": "12", "size": "6245", "license": "bsd-3-clause", "hash": -1401863079450919700, "line_mean": 27.7788018433, "line_max": 95, "alpha_frac": 0.6478783026, "autogenerated": false, "ratio": 3.504489337822671, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.020792894479813005, "num_lines": 217 }
""" General descriptor testing code """ from __future__ import print_function from rdkit import RDConfig import unittest,os.path import io from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import Descriptors from rdkit.Chem import AllChem from rdkit.Chem import rdMolDescriptors import numpy as np def feq(n1,n2,tol=1e-4): return abs(n1-n2)<=tol class TestCase(unittest.TestCase): def testBadAtomHandling(self): smis = ('CC[Pu]','CC[*]') for smi in smis: m = Chem.MolFromSmiles(smi) self.assertTrue(m) for nm,fn in Descriptors._descList: try: v = fn(m) except: import traceback traceback.print_exc() self.assertTrue(0,'SMILES: %s'%smi) def testMolFormula(self): for (smiles, expected) in ( ("[NH4+]", "H4N+"), ("c1ccccc1", "C6H6"), ("C1CCCCC1", "C6H12"), ("c1ccccc1O", "C6H6O"), ("C1CCCCC1O", "C6H12O"), ("C1CCCCC1=O", "C6H10O"), ("N[Na]", "H2NNa"), ("[C-][C-]", "C2-2"), ("[H]", "H"), ("[H-1]", "H-"), ("[H-1]", "H-"), ("[CH2]", "CH2"), ("[He-2]", "He-2"), ("[U+3]", "U+3"), ): mol = Chem.MolFromSmiles(smiles) actual = AllChem.CalcMolFormula(mol) self.assertEqual(actual,expected) def testMQNDetails(self): refFile = os.path.join(RDConfig.RDCodeDir,'Chem','test_data','MQNs_regress.pkl') with open(refFile,'r') as intf: buf = intf.read().replace('\r\n', '\n').encode('utf-8') intf.close() with io.BytesIO(buf) as inf: pkl = inf.read() refData = cPickle.loads(pkl,encoding='bytes') fn = os.path.join(RDConfig.RDCodeDir,'Chem','test_data','aromat_regress.txt') ms = [x for x in Chem.SmilesMolSupplier(fn,delimiter='\t')] for i,m in enumerate(ms): mqns = rdMolDescriptors.MQNs_(m) if mqns!=refData[i][1]: indices=[(j,x,y) for j,x,y in zip(range(len(mqns)),mqns,refData[i][1]) if x!=y] print(Chem.MolToSmiles(m),indices) self.assertEqual(mqns,refData[i][1]) def testMQN(self): tgt = np.array([42917, 274, 870, 621, 135, 1582, 29, 3147, 5463, 6999, 470, 81, 19055, 4424, 309, 24061, 17820, 1, 8314, 24146, 16076, 5560, 4262, 646, 746, 13725, 5430, 2629, 362, 24211, 15939, 292, 41, 20, 1852, 5642, 31, 9, 1, 2, 3060, 1750]) fn = os.path.join(RDConfig.RDCodeDir,'Chem','test_data','aromat_regress.txt') ms = [x for x in Chem.SmilesMolSupplier(fn,delimiter='\t')] vs = np.zeros((42,),np.int32) for m in ms: vs += rdMolDescriptors.MQNs_(m) self.assertFalse(False in (vs==tgt)) # - - - - - if __name__ == '__main__': import sys,getopt,re doLong=0 if len(sys.argv) >1: args,extras=getopt.getopt(sys.argv[1:],'l') for arg,val in args: if arg=='-l': doLong=1 sys.argv.remove('-l') if doLong: for methName in dir(TestCase): if re.match('_test',methName): newName = re.sub('_test','test',methName) exec('TestCase.%s = TestCase.%s'%(newName,methName)) unittest.main()
{ "repo_name": "strets123/rdkit", "path": "rdkit/Chem/UnitTestDescriptors.py", "copies": "1", "size": "3834", "license": "bsd-3-clause", "hash": -284687268025460300, "line_mean": 34.5, "line_max": 87, "alpha_frac": 0.5203442879, "autogenerated": false, "ratio": 3.0404440919904836, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8892932213662621, "avg_score": 0.03357123324557255, "num_lines": 108 }
""" General descriptor testing code """ from rdkit import RDConfig import unittest,os.path from rdkit import Chem from rdkit.Chem import Descriptors from rdkit.Chem import AllChem from rdkit.Chem import rdMolDescriptors import numpy as np def feq(n1,n2,tol=1e-4): return abs(n1-n2)<=tol class TestCase(unittest.TestCase): def testBadAtomHandling(self): smis = ('CC[Pu]','CC[*]') for smi in smis: m = Chem.MolFromSmiles(smi) self.failUnless(m) for nm,fn in Descriptors._descList: try: v = fn(m) except: import traceback traceback.print_exc() self.failUnless(0,'SMILES: %s'%smi) def testMolFormula(self): for (smiles, expected) in ( ("[NH4+]", "H4N+"), ("c1ccccc1", "C6H6"), ("C1CCCCC1", "C6H12"), ("c1ccccc1O", "C6H6O"), ("C1CCCCC1O", "C6H12O"), ("C1CCCCC1=O", "C6H10O"), ("N[Na]", "H2NNa"), ("[C-][C-]", "C2-2"), ("[H]", "H"), ("[H-1]", "H-"), ("[H-1]", "H-"), ("[CH2]", "CH2"), ("[He-2]", "He-2"), ("[U+3]", "U+3"), ): mol = Chem.MolFromSmiles(smiles) actual = AllChem.CalcMolFormula(mol) self.failUnlessEqual(actual,expected) def testMQN(self): tgt = np.array([42917, 274, 870, 621, 135, 1582, 29, 3147, 5463, 6999, 470, 81, 19055, 4424, 309, 24059, 17822, 1, 9303, 24146, 16076, 5560, 4262, 646, 746, 13725, 5430, 2629, 362, 24211, 15939, 292, 41, 20, 1852, 5642, 31, 9, 1, 2, 3060, 1750]) fn = os.path.join(RDConfig.RDCodeDir,'Chem','test_data','aromat_regress.txt') ms = [x for x in Chem.SmilesMolSupplier(fn,delimiter='\t')] vs = np.zeros((42,),np.int32) for m in ms: vs += rdMolDescriptors.MQNs_(m) self.failIf(False in (vs==tgt)) # - - - - - if __name__ == '__main__': import sys,getopt,re doLong=0 if len(sys.argv) >1: args,extras=getopt.getopt(sys.argv[1:],'l') for arg,val in args: if arg=='-l': doLong=1 sys.argv.remove('-l') if doLong: for methName in dir(TestCase): if re.match('_test',methName): newName = re.sub('_test','test',methName) exec('TestCase.%s = TestCase.%s'%(newName,methName)) unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/UnitTestDescriptors.py", "copies": "1", "size": "2992", "license": "bsd-3-clause", "hash": 138927306886013150, "line_mean": 32.6179775281, "line_max": 82, "alpha_frac": 0.4862967914, "autogenerated": false, "ratio": 3.103734439834025, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4090031231234025, "avg_score": null, "num_lines": null }
from __future__ import print_function _version = "0.14.0" _usage = """ SearchDb [optional arguments] <sdfilename> The sd filename argument can be either an SD file or an MDL mol file. NOTES: - The property names may have been altered on loading the database. Any non-alphanumeric character in a property name will be replaced with '_'. e.g."Gold.Goldscore.Constraint.Score" becomes "Gold_Goldscore_Constraint_Score". - Property names are not case sensitive in the database. """ from rdkit import RDConfig from rdkit.Dbase.DbConnection import DbConnect from rdkit.RDLogger import logger logger = logger() import zlib from rdkit import Chem from rdkit.Chem.MolDb.FingerprintUtils import supportedSimilarityMethods, BuildSigFactory, DepickleFP, LayeredOptions from rdkit.Chem.MolDb import FingerprintUtils from rdkit import DataStructs def _molFromPkl(pkl): if isinstance(pkl, (bytes, str)): mol = Chem.Mol(pkl) else: mol = Chem.Mol(str(pkl)) return mol def GetNeighborLists(probes, topN, pool, simMetric=DataStructs.DiceSimilarity, simThresh=-1., silent=False, **kwargs): probeFps = [x[1] for x in probes] validProbes = [x for x in range(len(probeFps)) if probeFps[x] is not None] validFps = [probeFps[x] for x in validProbes] from rdkit.DataStructs.TopNContainer import TopNContainer if simThresh <= 0: nbrLists = [TopNContainer(topN) for x in range(len(probeFps))] else: nbrLists = [TopNContainer(-1) for x in range(len(probeFps))] nDone = 0 for nm, fp in pool: nDone += 1 if not silent and not nDone % 1000: logger.info(' searched %d rows' % nDone) if (simMetric == DataStructs.DiceSimilarity): scores = DataStructs.BulkDiceSimilarity(fp, validFps) for i, score in enumerate(scores): if score > simThresh: nbrLists[validProbes[i]].Insert(score, nm) elif (simMetric == DataStructs.TanimotoSimilarity): scores = DataStructs.BulkTanimotoSimilarity(fp, validFps) for i, score in enumerate(scores): if score > simThresh: nbrLists[validProbes[i]].Insert(score, nm) elif (simMetric == DataStructs.TverskySimilarity): av = float(kwargs.get('tverskyA', 0.5)) bv = float(kwargs.get('tverskyB', 0.5)) scores = DataStructs.BulkTverskySimilarity(fp, validFps, av, bv) for i, score in enumerate(scores): if score > simThresh: nbrLists[validProbes[i]].Insert(score, nm) else: for i in range(len(probeFps)): pfp = probeFps[i] if pfp is not None: score = simMetric(probeFps[i], fp) if score > simThresh: nbrLists[validProbes[i]].Insert(score, nm) return nbrLists def GetMolsFromSmilesFile(dataFilename, errFile, nameProp): dataFile = open(dataFilename, 'r') for idx, line in enumerate(dataFile): try: smi, nm = line.strip().split(' ') except ValueError: continue m = Chem.MolFromSmiles(smi) if not m: if errfile: print(idx, nm, smi, file=errfile) continue yield (nm, smi, m) def GetMolsFromSDFile(dataFilename, errFile, nameProp): suppl = Chem.SDMolSupplier(dataFilename) for idx, m in enumerate(suppl): if not m: if errFile: if hasattr(suppl, 'GetItemText'): d = suppl.GetItemText(idx) errFile.write(d) else: logger.warning('full error file support not complete') continue smi = Chem.MolToSmiles(m, True) if m.HasProp(nameProp): nm = m.GetProp(nameProp) if not nm: logger.warning('molecule found with empty name property') else: nm = 'Mol_%d' % (idx + 1) yield nm, smi, m def RunSearch(options, queryFilename): global sigFactory if options.similarityType == 'AtomPairs': fpBuilder = FingerprintUtils.BuildAtomPairFP simMetric = DataStructs.DiceSimilarity dbName = os.path.join(options.dbDir, options.pairDbName) fpTableName = options.pairTableName fpColName = options.pairColName elif options.similarityType == 'TopologicalTorsions': fpBuilder = FingerprintUtils.BuildTorsionsFP simMetric = DataStructs.DiceSimilarity dbName = os.path.join(options.dbDir, options.torsionsDbName) fpTableName = options.torsionsTableName fpColName = options.torsionsColName elif options.similarityType == 'RDK': fpBuilder = FingerprintUtils.BuildRDKitFP simMetric = DataStructs.FingerprintSimilarity dbName = os.path.join(options.dbDir, options.fpDbName) fpTableName = options.fpTableName if not options.fpColName: options.fpColName = 'rdkfp' fpColName = options.fpColName elif options.similarityType == 'Pharm2D': fpBuilder = FingerprintUtils.BuildPharm2DFP simMetric = DataStructs.DiceSimilarity dbName = os.path.join(options.dbDir, options.fpDbName) fpTableName = options.pharm2DTableName if not options.fpColName: options.fpColName = 'pharm2dfp' fpColName = options.fpColName FingerprintUtils.sigFactory = BuildSigFactory(options) elif options.similarityType == 'Gobbi2D': from rdkit.Chem.Pharm2D import Gobbi_Pharm2D fpBuilder = FingerprintUtils.BuildPharm2DFP simMetric = DataStructs.TanimotoSimilarity dbName = os.path.join(options.dbDir, options.fpDbName) fpTableName = options.gobbi2DTableName if not options.fpColName: options.fpColName = 'gobbi2dfp' fpColName = options.fpColName FingerprintUtils.sigFactory = Gobbi_Pharm2D.factory elif options.similarityType == 'Morgan': fpBuilder = FingerprintUtils.BuildMorganFP simMetric = DataStructs.DiceSimilarity dbName = os.path.join(options.dbDir, options.morganFpDbName) fpTableName = options.morganFpTableName fpColName = options.morganFpColName extraArgs = {} if options.similarityMetric == 'tanimoto': simMetric = DataStructs.TanimotoSimilarity elif options.similarityMetric == 'dice': simMetric = DataStructs.DiceSimilarity elif options.similarityMetric == 'tversky': simMetric = DataStructs.TverskySimilarity extraArgs['tverskyA'] = options.tverskyA extraArgs['tverskyB'] = options.tverskyB if options.smilesQuery: mol = Chem.MolFromSmiles(options.smilesQuery) if not mol: logger.error('could not build query molecule from smiles "%s"' % options.smilesQuery) sys.exit(-1) options.queryMol = mol elif options.smartsQuery: mol = Chem.MolFromSmarts(options.smartsQuery) if not mol: logger.error('could not build query molecule from smarts "%s"' % options.smartsQuery) sys.exit(-1) options.queryMol = mol if options.outF == '-': outF = sys.stdout elif options.outF == '': outF = None else: outF = open(options.outF, 'w+') molsOut = False if options.sdfOut: molsOut = True if options.sdfOut == '-': sdfOut = sys.stdout else: sdfOut = open(options.sdfOut, 'w+') else: sdfOut = None if options.smilesOut: molsOut = True if options.smilesOut == '-': smilesOut = sys.stdout else: smilesOut = open(options.smilesOut, 'w+') else: smilesOut = None if queryFilename: try: tmpF = open(queryFilename, 'r') except IOError: logger.error('could not open query file %s' % queryFilename) sys.exit(1) if options.molFormat == 'smiles': func = GetMolsFromSmilesFile elif options.molFormat == 'sdf': func = GetMolsFromSDFile if not options.silent: msg = 'Reading query molecules' if fpBuilder: msg += ' and generating fingerprints' logger.info(msg) probes = [] i = 0 nms = [] for nm, smi, mol in func(queryFilename, None, options.nameProp): i += 1 nms.append(nm) if not mol: logger.error('query molecule %d could not be built' % (i)) probes.append((None, None)) continue if fpBuilder: probes.append((mol, fpBuilder(mol))) else: probes.append((mol, None)) if not options.silent and not i % 1000: logger.info(" done %d" % i) else: probes = None conn = None idName = options.molIdName ids = None names = None molDbName = os.path.join(options.dbDir, options.molDbName) molIdName = options.molIdName mConn = DbConnect(molDbName) cns = [(x.lower(), y) for x, y in mConn.GetColumnNamesAndTypes('molecules')] idCol, idTyp = cns[0] if options.propQuery or options.queryMol: conn = DbConnect(molDbName) curs = conn.GetCursor() if options.queryMol: if not options.silent: logger.info('Doing substructure query') if options.propQuery: where = 'where %s' % options.propQuery else: where = '' if not options.silent: curs.execute('select count(*) from molecules %(where)s' % locals()) nToDo = curs.fetchone()[0] join = '' doSubstructFPs = False fpDbName = os.path.join(options.dbDir, options.fpDbName) if os.path.exists(fpDbName) and not options.negateQuery: curs.execute("attach database '%s' as fpdb" % (fpDbName)) try: curs.execute('select * from fpdb.%s limit 1' % options.layeredTableName) except Exception: pass else: doSubstructFPs = True join = 'join fpdb.%s using (%s)' % (options.layeredTableName, idCol) query = LayeredOptions.GetQueryText(options.queryMol) if query: if not where: where = 'where' else: where += ' and' where += ' ' + query cmd = 'select %(idCol)s,molpkl from molecules %(join)s %(where)s' % locals() curs.execute(cmd) row = curs.fetchone() nDone = 0 ids = [] while row: id, molpkl = row if not options.zipMols: m = _molFromPkl(molpkl) else: m = Chem.Mol(zlib.decompress(molpkl)) matched = m.HasSubstructMatch(options.queryMol) if options.negateQuery: matched = not matched if matched: ids.append(id) nDone += 1 if not options.silent and not nDone % 500: if not doSubstructFPs: logger.info(' searched %d (of %d) molecules; %d hits so far' % (nDone, nToDo, len(ids))) else: logger.info(' searched through %d molecules; %d hits so far' % (nDone, len(ids))) row = curs.fetchone() if not options.silent and doSubstructFPs and nToDo: nFiltered = nToDo - nDone logger.info(' Fingerprint screenout rate: %d of %d (%%%.2f)' % (nFiltered, nToDo, 100. * nFiltered / nToDo)) elif options.propQuery: if not options.silent: logger.info('Doing property query') propQuery = options.propQuery.split(';')[0] curs.execute('select %(idCol)s from molecules where %(propQuery)s' % locals()) ids = [x[0] for x in curs.fetchall()] if not options.silent: logger.info('Found %d molecules matching the query' % (len(ids))) t1 = time.time() if probes: if not options.silent: logger.info('Finding Neighbors') conn = DbConnect(dbName) cns = conn.GetColumnNames(fpTableName) curs = conn.GetCursor() if ids: ids = [(x, ) for x in ids] curs.execute('create temporary table _tmpTbl (%(idCol)s %(idTyp)s)' % locals()) curs.executemany('insert into _tmpTbl values (?)', ids) join = 'join _tmpTbl using (%(idCol)s)' % locals() else: join = '' if cns[0].lower() != idCol.lower(): # backwards compatibility to the days when mol tables had a guid and # the fps tables did not: curs.execute("attach database '%(molDbName)s' as mols" % locals()) curs.execute(""" select %(idCol)s,%(fpColName)s from %(fpTableName)s join (select %(idCol)s,%(molIdName)s from mols.molecules %(join)s) using (%(molIdName)s) """ % (locals())) else: curs.execute('select %(idCol)s,%(fpColName)s from %(fpTableName)s %(join)s' % locals()) def poolFromCurs(curs, similarityMethod): row = curs.fetchone() while row: id, pkl = row fp = DepickleFP(pkl, similarityMethod) yield (id, fp) row = curs.fetchone() topNLists = GetNeighborLists(probes, options.topN, poolFromCurs(curs, options.similarityType), simMetric=simMetric, simThresh=options.simThresh, **extraArgs) uniqIds = set() nbrLists = {} for i, nm in enumerate(nms): topNLists[i].reverse() scores = topNLists[i].GetPts() nbrNames = topNLists[i].GetExtras() nbrs = [] for j, nbrGuid in enumerate(nbrNames): if nbrGuid is None: break else: uniqIds.add(nbrGuid) nbrs.append((nbrGuid, scores[j])) nbrLists[(i, nm)] = nbrs t2 = time.time() if not options.silent: logger.info('The search took %.1f seconds' % (t2 - t1)) if not options.silent: logger.info('Creating output') curs = mConn.GetCursor() ids = list(uniqIds) ids = [(x, ) for x in ids] curs.execute('create temporary table _tmpTbl (%(idCol)s %(idTyp)s)' % locals()) curs.executemany('insert into _tmpTbl values (?)', ids) curs.execute('select %(idCol)s,%(molIdName)s from molecules join _tmpTbl using (%(idCol)s)' % locals()) nmDict = {} for guid, id in curs.fetchall(): nmDict[guid] = str(id) ks = list(nbrLists.keys()) ks.sort() if not options.transpose: for i, nm in ks: nbrs = nbrLists[(i, nm)] nbrTxt = options.outputDelim.join([nm] + ['%s%s%.3f' % (nmDict[id], options.outputDelim, score) for id, score in nbrs]) if outF: print(nbrTxt, file=outF) else: labels = ['%s%sSimilarity' % (x[1], options.outputDelim) for x in ks] if outF: print(options.outputDelim.join(labels), file=outF) for i in range(options.topN): outL = [] for idx, nm in ks: nbr = nbrLists[(idx, nm)][i] outL.append(nmDict[nbr[0]]) outL.append('%.3f' % nbr[1]) if outF: print(options.outputDelim.join(outL), file=outF) else: if not options.silent: logger.info('Creating output') curs = mConn.GetCursor() ids = [(x, ) for x in set(ids)] curs.execute('create temporary table _tmpTbl (%(idCol)s %(idTyp)s)' % locals()) curs.executemany('insert into _tmpTbl values (?)', ids) molIdName = options.molIdName curs.execute('select %(idCol)s,%(molIdName)s from molecules join _tmpTbl using (%(idCol)s)' % locals()) nmDict = {} for guid, id in curs.fetchall(): nmDict[guid] = str(id) if outF: print('\n'.join(nmDict.values()), file=outF) if molsOut and ids: molDbName = os.path.join(options.dbDir, options.molDbName) cns = [x.lower() for x in mConn.GetColumnNames('molecules')] if cns[-1] != 'molpkl': cns.remove('molpkl') cns.append('molpkl') curs = mConn.GetCursor() #curs.execute('create temporary table _tmpTbl (guid integer)'%locals()) #curs.executemany('insert into _tmpTbl values (?)',ids) cnText = ','.join(cns) curs.execute('select %(cnText)s from molecules join _tmpTbl using (%(idCol)s)' % locals()) row = curs.fetchone() molD = {} while row: row = list(row) m = _molFromPkl(row[-1]) guid = row[0] nm = nmDict[guid] if sdfOut: m.SetProp('_Name', nm) print(Chem.MolToMolBlock(m), file=sdfOut) for i in range(1, len(cns) - 1): pn = cns[i] pv = str(row[i]) print >> sdfOut, '> <%s>\n%s\n' % (pn, pv) print('$$$$', file=sdfOut) if smilesOut: smi = Chem.MolToSmiles(m, options.chiralSmiles) if smilesOut: print('%s %s' % (smi, str(row[1])), file=smilesOut) row = curs.fetchone() if not options.silent: logger.info('Done!') # ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- import os from optparse import OptionParser parser = OptionParser(_usage, version='%prog ' + _version) parser.add_option( '--dbDir', default='/db/camm/CURRENT/rdk_db', help='name of the directory containing the database information. The default is %default') parser.add_option('--molDbName', default='Compounds.sqlt', help='name of the molecule database') parser.add_option('--molIdName', default='compound_id', help='name of the database key column') parser.add_option('--regName', default='molecules', help='name of the molecular registry table') parser.add_option('--pairDbName', default='AtomPairs.sqlt', help='name of the atom pairs database') parser.add_option('--pairTableName', default='atompairs', help='name of the atom pairs table') parser.add_option('--pairColName', default='atompairfp', help='name of the atom pair column') parser.add_option( '--torsionsDbName', default='AtomPairs.sqlt', help='name of the topological torsions database (usually the same as the atom pairs database)') parser.add_option( '--torsionsTableName', default='atompairs', help='name of the topological torsions table (usually the same as the atom pairs table)') parser.add_option('--torsionsColName', default='torsionfp', help='name of the atom pair column') parser.add_option('--fpDbName', default='Fingerprints.sqlt', help='name of the 2D fingerprints database') parser.add_option('--fpTableName', default='rdkitfps', help='name of the 2D fingerprints table') parser.add_option('--layeredTableName', default='layeredfps', help='name of the layered fingerprints table') parser.add_option('--fpColName', default='', help='name of the 2D fingerprint column, a sensible default is used') parser.add_option('--descrDbName', default='Descriptors.sqlt', help='name of the descriptor database') parser.add_option('--descrTableName', default='descriptors_v1', help='name of the descriptor table') parser.add_option('--descriptorCalcFilename', default=os.path.join(RDConfig.RDBaseDir, 'Projects', 'DbCLI', 'moe_like.dsc'), help='name of the file containing the descriptor calculator') parser.add_option('--outputDelim', default=',', help='the delimiter for the output file. The default is %default') parser.add_option( '--topN', default=20, type='int', help='the number of neighbors to keep for each query compound. The default is %default') parser.add_option('--outF', '--outFile', default='-', help='The name of the output file. The default is the console (stdout).') parser.add_option( '--transpose', default=False, action="store_true", help='print the results out in a transposed form: e.g. neighbors in rows and probe compounds in columns') parser.add_option('--molFormat', default='sdf', choices=('smiles', 'sdf'), help='specify the format of the input file') parser.add_option( '--nameProp', default='_Name', help='specify the SD property to be used for the molecule names. Default is to use the mol block name') parser.add_option('--smartsQuery', '--smarts', '--sma', default='', help='provide a SMARTS to be used as a substructure query') parser.add_option('--smilesQuery', '--smiles', '--smi', default='', help='provide a SMILES to be used as a substructure query') parser.add_option('--negateQuery', '--negate', default=False, action='store_true', help='negate the results of the smarts query.') parser.add_option('--propQuery', '--query', '-q', default='', help='provide a property query (see the NOTE about property names)') parser.add_option('--sdfOut', '--sdOut', default='', help='export an SD file with the matching molecules') parser.add_option('--smilesOut', '--smiOut', default='', help='export a smiles file with the matching molecules') parser.add_option('--nonchiralSmiles', dest='chiralSmiles', default=True, action='store_false', help='do not use chiral SMILES in the output') parser.add_option('--silent', default=False, action='store_true', help='Do not generate status messages.') parser.add_option('--zipMols', '--zip', default=False, action='store_true', help='read compressed mols from the database') parser.add_option('--pharm2DTableName', default='pharm2dfps', help='name of the Pharm2D fingerprints table') parser.add_option('--fdefFile', '--fdef', default=os.path.join(RDConfig.RDDataDir, 'Novartis1.fdef'), help='provide the name of the fdef file to use for 2d pharmacophores') parser.add_option('--gobbi2DTableName', default='gobbi2dfps', help='name of the Gobbi2D fingerprints table') parser.add_option( '--similarityType', '--simType', '--sim', default='RDK', choices=supportedSimilarityMethods, help='Choose the type of similarity to use, possible values: RDK, AtomPairs, TopologicalTorsions, Pharm2D, Gobbi2D, Avalon, Morgan. The default is %default') parser.add_option('--morganFpDbName', default='Fingerprints.sqlt', help='name of the morgan fingerprints database') parser.add_option('--morganFpTableName', default='morganfps', help='name of the morgan fingerprints table') parser.add_option('--morganFpColName', default='morganfp', help='name of the morgan fingerprint column') parser.add_option( '--similarityMetric', '--simMetric', '--metric', default='', choices=('tanimoto', 'dice', 'tversky', ''), help='Choose the type of similarity to use, possible values: tanimoto, dice, tversky. The default is determined by the fingerprint type') parser.add_option('--tverskyA', default=0.5, type='float', help='Tversky A value') parser.add_option('--tverskyB', default=0.5, type='float', help='Tversky B value') parser.add_option( '--simThresh', default=-1, type='float', help='threshold to use for similarity searching. If provided, this supersedes the topN argument') if __name__ == '__main__': import sys, getopt, time options, args = parser.parse_args() if len(args) != 1 and not (options.smilesQuery or options.smartsQuery or options.propQuery): parser.error('please either provide a query filename argument or do a data or smarts query') if len(args): queryFilename = args[0] else: queryFilename = None options.queryMol = None RunSearch(options, queryFilename)
{ "repo_name": "rvianello/rdkit", "path": "Projects/DbCLI/SearchDb.py", "copies": "2", "size": "24469", "license": "bsd-3-clause", "hash": -5270278886774223000, "line_mean": 38.2131410256, "line_max": 159, "alpha_frac": 0.6483305407, "autogenerated": false, "ratio": 3.5091065538505664, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5157437094550565, "avg_score": null, "num_lines": null }
from __future__ import print_function import unittest import os,sys from rdkit.six.moves import cPickle from rdkit import rdBase from rdkit import Chem from rdkit.Chem import rdChemReactions from rdkit import Geometry from rdkit import RDConfig def feq(v1,v2,tol2=1e-4): return abs(v1-v2)<=tol2 def ptEq(pt1, pt2, tol=1e-4): return feq(pt1.x,pt2.x,tol) and feq(pt1.y,pt2.y,tol) and feq(pt1.z,pt2.z,tol) class TestCase(unittest.TestCase) : def setUp(self): self.dataDir = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','ChemReactions','testData') def test1Basics(self): rxn = rdChemReactions.ChemicalReaction() self.assertTrue(rxn.GetNumReactantTemplates()==0) self.assertTrue(rxn.GetNumProductTemplates()==0) r1= Chem.MolFromSmarts('[C:1](=[O:2])O') rxn.AddReactantTemplate(r1) self.assertTrue(rxn.GetNumReactantTemplates()==1) r1= Chem.MolFromSmarts('[N:3]') rxn.AddReactantTemplate(r1) self.assertTrue(rxn.GetNumReactantTemplates()==2) r1= Chem.MolFromSmarts('[C:1](=[O:2])[N:3]') rxn.AddProductTemplate(r1) self.assertTrue(rxn.GetNumProductTemplates()==1) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) self.assertTrue(len(ps)==1) self.assertTrue(len(ps[0])==1) self.assertTrue(ps[0][0].GetNumAtoms()==3) ps = rxn.RunReactants(list(reacts)) self.assertTrue(len(ps)==1) self.assertTrue(len(ps[0])==1) self.assertTrue(ps[0][0].GetNumAtoms()==3) def test2DaylightParser(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]') self.assertTrue(rxn) self.assertTrue(rxn.GetNumReactantTemplates()==2) self.assertTrue(rxn.GetNumProductTemplates()==1) self.assertTrue(rxn._getImplicitPropertiesFlag()) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) self.assertTrue(len(ps)==1) self.assertTrue(len(ps[0])==1) self.assertTrue(ps[0][0].GetNumAtoms()==3) reacts = (Chem.MolFromSmiles('CC(=O)OC'),Chem.MolFromSmiles('CN')) ps = rxn.RunReactants(reacts) self.assertTrue(len(ps)==1) self.assertTrue(len(ps[0])==1) self.assertTrue(ps[0][0].GetNumAtoms()==5) def test3MDLParsers(self): fileN = os.path.join(self.dataDir,'AmideBond.rxn') rxn = rdChemReactions.ReactionFromRxnFile(fileN) self.assertTrue(rxn) self.assertFalse(rxn._getImplicitPropertiesFlag()) self.assertTrue(rxn.GetNumReactantTemplates()==2) self.assertTrue(rxn.GetNumProductTemplates()==1) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) self.assertTrue(len(ps)==1) self.assertTrue(len(ps[0])==1) self.assertTrue(ps[0][0].GetNumAtoms()==3) with open(fileN, 'r') as rxnF: rxnBlock = rxnF.read() rxn = rdChemReactions.ReactionFromRxnBlock(rxnBlock) self.assertTrue(rxn) self.assertTrue(rxn.GetNumReactantTemplates()==2) self.assertTrue(rxn.GetNumProductTemplates()==1) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) self.assertTrue(len(ps)==1) self.assertTrue(len(ps[0])==1) self.assertTrue(ps[0][0].GetNumAtoms()==3) def test4ErrorHandling(self): self.assertRaises(ValueError,lambda x='[C:1](=[O:2])Q.[N:3]>>[C:1](=[O:2])[N:3]':rdChemReactions.ReactionFromSmarts(x)) self.assertRaises(ValueError,lambda x='[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]Q':rdChemReactions.ReactionFromSmarts(x)) self.assertRaises(ValueError,lambda x='[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]>>CC':rdChemReactions.ReactionFromSmarts(x)) block="""$RXN ISIS 082120061354 3 1 $MOL -ISIS- 08210613542D 3 2 0 0 0 0 0 0 0 0999 V2000 -1.4340 -0.6042 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 -0.8639 -0.9333 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 -1.4340 0.0542 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 1 3 2 0 0 0 0 M END $MOL -ISIS- 08210613542D 1 0 0 0 0 0 0 0 0 0999 V2000 2.2125 -0.7833 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 M END $MOL -ISIS- 08210613542D 3 2 0 0 0 0 0 0 0 0999 V2000 9.5282 -0.8083 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 8.9579 -0.4792 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 8.9579 0.1792 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 2 3 2 0 0 0 0 M END """ self.assertRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) block="""$RXN ISIS 082120061354 2 1 $MOL -ISIS- 08210613542D 4 2 0 0 0 0 0 0 0 0999 V2000 -1.4340 -0.6042 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 -0.8639 -0.9333 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 -1.4340 0.0542 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 1 3 2 0 0 0 0 M END $MOL -ISIS- 08210613542D 1 0 0 0 0 0 0 0 0 0999 V2000 2.2125 -0.7833 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 M END $MOL -ISIS- 08210613542D 3 2 0 0 0 0 0 0 0 0999 V2000 9.5282 -0.8083 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 8.9579 -0.4792 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 8.9579 0.1792 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 2 3 2 0 0 0 0 M END """ #self.assertRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) block="""$RXN ISIS 082120061354 2 1 $MOL -ISIS- 08210613542D 3 2 0 0 0 0 0 0 0 0999 V2000 -1.4340 -0.6042 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 -0.8639 -0.9333 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 -1.4340 0.0542 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 1 3 2 0 0 0 0 M END $MOL -ISIS- 08210613542D 1 0 0 0 0 0 0 0 0 0999 V2000 2.2125 -0.7833 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 M END $MOL -ISIS- 08210613542D 3 1 0 0 0 0 0 0 0 0999 V2000 9.5282 -0.8083 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 8.9579 -0.4792 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 8.9579 0.1792 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 2 3 2 0 0 0 0 M END """ #self.assertRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) def test5Validation(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]') self.assertTrue(rxn) self.assertTrue(rxn.Validate()==(0,0)) rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:1])O.[N:3]>>[C:1](=[O:2])[N:3]') self.assertTrue(rxn) self.assertTrue(rxn.Validate()==(1,1)) rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])[O:4].[N:3]>>[C:1](=[O:2])[N:3]') self.assertTrue(rxn) self.assertTrue(rxn.Validate()==(1,0)) rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3][C:5]') self.assertTrue(rxn) self.assertTrue(rxn.Validate()==(1,0)) def test6Exceptions(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]Cl>>[C:1]') self.assertTrue(rxn) self.assertRaises(ValueError,lambda x=rxn:x.RunReactants(())) self.assertRaises(ValueError,lambda x=rxn:x.RunReactants((Chem.MolFromSmiles('CC'),Chem.MolFromSmiles('C')))) ps=rxn.RunReactants((Chem.MolFromSmiles('CCCl'),)) self.assertTrue(len(ps)==1) self.assertTrue(len(ps[0])==1) def _test7Leak(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]Cl>>[C:1]') self.assertTrue(rxn) print('running: ') for i in range(1e5): ps=rxn.RunReactants((Chem.MolFromSmiles('CCCl'),)) self.assertTrue(len(ps)==1) self.assertTrue(len(ps[0])==1) if not i%1000: print(i) def test8Properties(self): rxn = rdChemReactions.ReactionFromSmarts('[O:1]>>[O:1][3#0]') self.assertTrue(rxn) ps=rxn.RunReactants((Chem.MolFromSmiles('CO'),)) self.assertTrue(len(ps)==1) self.assertTrue(len(ps[0])==1) Chem.SanitizeMol(ps[0][0]) self.assertEqual(ps[0][0].GetAtomWithIdx(1).GetIsotope(),3); def test9AromaticityTransfer(self): # this was issue 2664121 mol = Chem.MolFromSmiles('c1ccc(C2C3(Cc4c(cccc4)C2)CCCC3)cc1') rxn = rdChemReactions.ReactionFromSmarts('[A:1]1~[*:2]~[*:3]~[*:4]~[*:5]~[A:6]-;@1>>[*:1]~[*:2]~[*:3]~[*:4]~[*:5]~[*:6]') products = rxn.RunReactants([mol]) self.assertEqual(len(products),6) for p in products: self.assertEqual(len(p),1) Chem.SanitizeMol(p[0]) def test10DotSeparation(self): # 08/05/14 # This test is changed due to a new behavior of the smarts # reaction parser which now allows using parenthesis in products # as well. original smiles: '[C:1]1[O:2][N:3]1>>[C:1]1[O:2].[N:3]1' rxn = rdChemReactions.ReactionFromSmarts('[C:1]1[O:2][N:3]1>>([C:1]1[O:2].[N:3]1)') mol = Chem.MolFromSmiles('C1ON1') products = rxn.RunReactants([mol]) self.assertEqual(len(products),1) for p in products: self.assertEqual(len(p),1) self.assertEqual(p[0].GetNumAtoms(),3) self.assertEqual(p[0].GetNumBonds(),2) def test11ImplicitProperties(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]O>>[C:1]') mol = Chem.MolFromSmiles('CCO') products = rxn.RunReactants([mol]) self.assertEqual(len(products),1) for p in products: self.assertEqual(len(p),1) self.assertEqual(Chem.MolToSmiles(p[0]),'CC') mol2 = Chem.MolFromSmiles('C[CH-]O') products = rxn.RunReactants([mol2]) self.assertEqual(len(products),1) for p in products: self.assertEqual(len(p),1) self.assertEqual(Chem.MolToSmiles(p[0]),'[CH2-]C') rxn._setImplicitPropertiesFlag(False) products = rxn.RunReactants([mol]) self.assertEqual(len(products),1) for p in products: self.assertEqual(len(p),1) self.assertEqual(Chem.MolToSmiles(p[0]),'CC') products = rxn.RunReactants([mol2]) self.assertEqual(len(products),1) for p in products: self.assertEqual(len(p),1) self.assertEqual(Chem.MolToSmiles(p[0]),'CC') def test12Pickles(self): # 08/05/14 # This test is changed due to a new behavior of the smarts # reaction parser which now allows using parenthesis in products # as well. original smiles: '[C:1]1[O:2][N:3]1>>[C:1]1[O:2].[N:3]1' rxn = rdChemReactions.ReactionFromSmarts('[C:1]1[O:2][N:3]1>>([C:1]1[O:2].[N:3]1)') pkl = cPickle.dumps(rxn) rxn = cPickle.loads(pkl) mol = Chem.MolFromSmiles('C1ON1') products = rxn.RunReactants([mol]) self.assertEqual(len(products),1) for p in products: self.assertEqual(len(p),1) self.assertEqual(p[0].GetNumAtoms(),3) self.assertEqual(p[0].GetNumBonds(),2) rxn = rdChemReactions.ChemicalReaction(rxn.ToBinary()) products = rxn.RunReactants([mol]) self.assertEqual(len(products),1) for p in products: self.assertEqual(len(p),1) self.assertEqual(p[0].GetNumAtoms(),3) self.assertEqual(p[0].GetNumBonds(),2) def test13GetTemplates(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]1[O:2][N:3]1>>[C:1][O:2].[N:3]') r1 = rxn.GetReactantTemplate(0) sma=Chem.MolToSmarts(r1) self.assertEqual(sma,'[C:1]1-,:[O:2]-,:[N:3]-,:1') p1 = rxn.GetProductTemplate(0) sma=Chem.MolToSmarts(p1) self.assertEqual(sma,'[C:1]-,:[O:2]') p2 = rxn.GetProductTemplate(1) sma=Chem.MolToSmarts(p2) self.assertEqual(sma,'[N:3]') self.assertRaises(ValueError,lambda :rxn.GetProductTemplate(2)) self.assertRaises(ValueError,lambda :rxn.GetReactantTemplate(1)) def test14Matchers(self): rxn = rdChemReactions.ReactionFromSmarts('[C;!$(C(-O)-O):1](=[O:2])[O;H,-1].[N;!H0:3]>>[C:1](=[O:2])[N:3]') self.assertTrue(rxn) rxn.Initialize() self.assertTrue(rxn.IsMoleculeReactant(Chem.MolFromSmiles('OC(=O)C'))) self.assertFalse(rxn.IsMoleculeReactant(Chem.MolFromSmiles('OC(=O)O'))) self.assertTrue(rxn.IsMoleculeReactant(Chem.MolFromSmiles('CNC'))) self.assertFalse(rxn.IsMoleculeReactant(Chem.MolFromSmiles('CN(C)C'))) self.assertTrue(rxn.IsMoleculeProduct(Chem.MolFromSmiles('NC(=O)C'))) self.assertTrue(rxn.IsMoleculeProduct(Chem.MolFromSmiles('CNC(=O)C'))) self.assertFalse(rxn.IsMoleculeProduct(Chem.MolFromSmiles('COC(=O)C'))) def test15Replacements(self): rxn = rdChemReactions.ReactionFromSmarts('[{amine}:1]>>[*:1]-C', replacements={'{amine}':'$([N;!H0;$(N-[#6]);!$(N-[!#6;!#1]);!$(N-C=[O,N,S])])'}) self.assertTrue(rxn) rxn.Initialize() reactants = (Chem.MolFromSmiles('CCN'),) ps = rxn.RunReactants(reactants) self.assertEqual(len(ps),1) self.assertEqual(len(ps[0]),1) self.assertEqual(ps[0][0].GetNumAtoms(),4) def test16GetReactingAtoms(self): rxn = rdChemReactions.ReactionFromSmarts("[O:1][C:2].[N:3]>>[N:1][C:2].[N:3]") self.assertTrue(rxn) rxn.Initialize() rAs = rxn.GetReactingAtoms() self.assertEqual(len(rAs),2) self.assertEqual(len(rAs[0]),1) self.assertEqual(len(rAs[1]),0) rxn = rdChemReactions.ReactionFromSmarts("[O:1]C>>[O:1]C") self.assertTrue(rxn) rxn.Initialize() rAs = rxn.GetReactingAtoms() self.assertEqual(len(rAs),1) self.assertEqual(len(rAs[0]),2) rAs = rxn.GetReactingAtoms(True) self.assertEqual(len(rAs),1) self.assertEqual(len(rAs[0]),1) def test17AddRecursiveQueriesToReaction(self): rxn = rdChemReactions.ReactionFromSmarts("[C:1][O:2].[N:3]>>[C:1][N:2]") self.assertTrue(rxn) rxn.Initialize() qs = {'aliphatic':Chem.MolFromSmiles('CC')} rxn.GetReactantTemplate(0).GetAtomWithIdx(0).SetProp('query', 'aliphatic') rxn.AddRecursiveQueriesToReaction(qs,'query') q = rxn.GetReactantTemplate(0) m = Chem.MolFromSmiles('CCOC') self.assertTrue(m.HasSubstructMatch(q)) m = Chem.MolFromSmiles('CO') self.assertFalse(m.HasSubstructMatch(q)) rxn = rdChemReactions.ReactionFromSmarts("[C:1][O:2].[N:3]>>[C:1][N:2]") rxn.Initialize() rxn.GetReactantTemplate(0).GetAtomWithIdx(0).SetProp('query', 'aliphatic') labels = rxn.AddRecursiveQueriesToReaction(qs,'query', getLabels=True) self.assertTrue(len(labels), 1) def test18GithubIssue16(self): rxn = rdChemReactions.ReactionFromSmarts("[F:1]>>[Cl:1]") self.assertTrue(rxn) rxn.Initialize() self.assertRaises(ValueError,lambda : rxn.RunReactants((None,))) def test19RemoveUnmappedMoleculesToAgents(self): rxn = rdChemReactions.ReactionFromSmarts("[C:1]=[O:2].[N:3].C(=O)O>[OH2].[Na].[Cl]>[N:3]~[C:1]=[O:2]") self.failUnless(rxn) rxn.Initialize() self.failUnless(rxn.GetNumReactantTemplates()==3) self.failUnless(rxn.GetNumProductTemplates()==1) self.failUnless(rxn.GetNumAgentTemplates()==3) rxn.RemoveUnmappedReactantTemplates() rxn.RemoveUnmappedProductTemplates() self.failUnless(rxn.GetNumReactantTemplates()==2) self.failUnless(rxn.GetNumProductTemplates()==1) self.failUnless(rxn.GetNumAgentTemplates()==4) rxn = rdChemReactions.ReactionFromSmarts("[C:1]=[O:2].[N:3].C(=O)O>>[N:3]~[C:1]=[O:2].[OH2]") self.failUnless(rxn) rxn.Initialize() self.failUnless(rxn.GetNumReactantTemplates()==3) self.failUnless(rxn.GetNumProductTemplates()==2) self.failUnless(rxn.GetNumAgentTemplates()==0) agentList=[] rxn.RemoveUnmappedReactantTemplates(moveToAgentTemplates=False, targetList=agentList) rxn.RemoveUnmappedProductTemplates(targetList=agentList) self.failUnless(rxn.GetNumReactantTemplates()==2) self.failUnless(rxn.GetNumProductTemplates()==1) self.failUnless(rxn.GetNumAgentTemplates()==1) self.failUnless(len(agentList)==2) if __name__ == '__main__': unittest.main()
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "Code/GraphMol/ChemReactions/Wrap/testReactionWrapper.py", "copies": "1", "size": "17739", "license": "bsd-3-clause", "hash": 4263862272967201300, "line_mean": 35.6508264463, "line_max": 127, "alpha_frac": 0.6400022549, "autogenerated": false, "ratio": 2.5873687281213535, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37273709830213536, "avg_score": null, "num_lines": null }
from __future__ import print_function from rdkit import Chem, Geometry from rdkit.Chem import AllChem from rdkit.Chem.Subshape import SubshapeObjects from rdkit.Chem.Subshape import BuilderUtils from rdkit.six.moves import cPickle import time #----------------------------------------------------------------------------- class SubshapeCombineOperations(object): UNION = 0 SUM = 1 INTERSECT = 2 #----------------------------------------------------------------------------- class SubshapeBuilder(object): gridDims = (20, 15, 10) gridSpacing = 0.5 winRad = 3.0 nbrCount = 7 terminalPtRadScale = 0.75 fraction = 0.25 stepSize = 1.0 featFactory = None def SampleSubshape(self, subshape1, newSpacing): ogrid = subshape1.grid rgrid = Geometry.UniformGrid3D(self.gridDims[0], self.gridDims[1], self.gridDims[2], newSpacing) for idx in range(rgrid.GetSize()): l = rgrid.GetGridPointLoc(idx) v = ogrid.GetValPoint(l) rgrid.SetVal(idx, v) res = SubshapeObjects.ShapeWithSkeleton() res.grid = rgrid return res def GenerateSubshapeShape(self, cmpd, confId=-1, addSkeleton=True, **kwargs): shape = SubshapeObjects.ShapeWithSkeleton() shape.grid = Geometry.UniformGrid3D(self.gridDims[0], self.gridDims[1], self.gridDims[2], self.gridSpacing) AllChem.EncodeShape(cmpd, shape.grid, ignoreHs=False, confId=confId) if addSkeleton: conf = cmpd.GetConformer(confId) self.GenerateSubshapeSkeleton(shape, conf, kwargs) return shape def __call__(self, cmpd, **kwargs): return self.GenerateSubshapeShape(cmpd, **kwargs) def GenerateSubshapeSkeleton(self, shape, conf=None, terminalPtsOnly=False, skelFromConf=True): if conf and skelFromConf: pts = BuilderUtils.FindTerminalPtsFromConformer(conf, self.winRad, self.nbrCount) else: pts = BuilderUtils.FindTerminalPtsFromShape(shape, self.winRad, self.fraction) pts = BuilderUtils.ClusterTerminalPts(pts, self.winRad, self.terminalPtRadScale) BuilderUtils.ExpandTerminalPts(shape, pts, self.winRad) if len(pts) < 3: raise ValueError('only found %d terminals, need at least 3' % len(pts)) if not terminalPtsOnly: pts = BuilderUtils.AppendSkeletonPoints(shape.grid, pts, self.winRad, self.stepSize) for i, pt in enumerate(pts): BuilderUtils.CalculateDirectionsAtPoint(pt, shape.grid, self.winRad) if conf and self.featFactory: BuilderUtils.AssignMolFeatsToPoints(pts, conf.GetOwningMol(), self.featFactory, self.winRad) shape.skelPts = pts def CombineSubshapes(self, subshape1, subshape2, operation=SubshapeCombineOperations.UNION): import copy cs = copy.deepcopy(subshape1) if operation == SubshapeCombineOperations.UNION: cs.grid |= subshape2.grid elif operation == SubshapeCombineOperations.SUM: cs.grid += subshape2.grid elif operation == SubshapeCombineOperations.INTERSECT: cs.grid &= subshape2.grid else: raise ValueError('bad combination operation') return cs if __name__ == '__main__': from rdkit.Chem import AllChem, ChemicalFeatures from rdkit.Chem.PyMol import MolViewer #cmpd = Chem.MolFromSmiles('CCCc1cc(C(=O)O)ccc1') #cmpd = Chem.AddHs(cmpd) if 1: cmpd = Chem.MolFromSmiles('C1=CC=C1C#CC1=CC=C1') cmpd = Chem.AddHs(cmpd) AllChem.EmbedMolecule(cmpd) AllChem.UFFOptimizeMolecule(cmpd) AllChem.CanonicalizeMol(cmpd) print(Chem.MolToMolBlock(cmpd), file=file('testmol.mol', 'w+')) else: cmpd = Chem.MolFromMolFile('testmol.mol') builder = SubshapeBuilder() if 1: shape = builder.GenerateSubshapeShape(cmpd) v = MolViewer() if 1: import tempfile tmpFile = tempfile.mktemp('.grd') v.server.deleteAll() Geometry.WriteGridToFile(shape.grid, tmpFile) time.sleep(1) v.ShowMol(cmpd, name='testMol', showOnly=True) v.server.loadSurface(tmpFile, 'testGrid', '', 2.5) v.server.resetCGO('*') cPickle.dump(shape, file('subshape.pkl', 'w+')) for i, pt in enumerate(shape.skelPts): v.server.sphere(tuple(pt.location), .5, (1, 0, 1), 'Pt-%d' % i) if not hasattr(pt, 'shapeDirs'): continue momBeg = pt.location - pt.shapeDirs[0] momEnd = pt.location + pt.shapeDirs[0] v.server.cylinder(tuple(momBeg), tuple(momEnd), .1, (1, 0, 1), 'v-%d' % i)
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Subshape/SubshapeBuilder.py", "copies": "1", "size": "4434", "license": "bsd-3-clause", "hash": 781879999306658000, "line_mean": 34.472, "line_max": 100, "alpha_frac": 0.6741091565, "autogenerated": false, "ratio": 3.1694067190850608, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43435158755850606, "avg_score": null, "num_lines": null }
from rdkit import Chem,Geometry from rdkit.Chem import AllChem from rdkit.Chem.Subshape import SubshapeObjects from rdkit.Chem.Subshape import BuilderUtils from rdkit.six.moves import cPickle import time #----------------------------------------------------------------------------- class SubshapeCombineOperations(object): UNION=0 SUM=1 INTERSECT=2 #----------------------------------------------------------------------------- class SubshapeBuilder(object): gridDims=(20,15,10) gridSpacing=0.5 winRad=3.0 nbrCount=7 terminalPtRadScale=0.75 fraction=0.25 stepSize=1.0 featFactory=None def SampleSubshape(self,subshape1,newSpacing): ogrid=subshape1.grid rgrid = Geometry.UniformGrid3D(self.gridDims[0],self.gridDims[1],self.gridDims[2], newSpacing) for idx in range(rgrid.GetSize()): l = rgrid.GetGridPointLoc(idx) v = ogrid.GetValPoint(l) rgrid.SetVal(idx,v) res = SubshapeObjects.ShapeWithSkeleton() res.grid = rgrid return res; def GenerateSubshapeShape(self,cmpd,confId=-1,addSkeleton=True,**kwargs): shape = SubshapeObjects.ShapeWithSkeleton() shape.grid=Geometry.UniformGrid3D(self.gridDims[0],self.gridDims[1],self.gridDims[2], self.gridSpacing) AllChem.EncodeShape(cmpd,shape.grid,ignoreHs=False,confId=confId) if addSkeleton: conf = cmpd.GetConformer(confId) self.GenerateSubshapeSkeleton(shape,conf,kwargs) return shape def __call__(self,cmpd,**kwargs): return self.GenerateSubshapeShape(cmpd,**kwargs) def GenerateSubshapeSkeleton(self,shape,conf=None,terminalPtsOnly=False,skelFromConf=True): if conf and skelFromConf: pts = BuilderUtils.FindTerminalPtsFromConformer(conf,self.winRad,self.nbrCount) else: pts = BuilderUtils.FindTerminalPtsFromShape(shape,self.winRad,self.fraction) pts = BuilderUtils.ClusterTerminalPts(pts,self.winRad,self.terminalPtRadScale) BuilderUtils.ExpandTerminalPts(shape,pts,self.winRad) if len(pts)<3: raise ValueError('only found %d terminals, need at least 3'%len(pts)) if not terminalPtsOnly: pts = BuilderUtils.AppendSkeletonPoints(shape.grid,pts,self.winRad,self.stepSize) for i,pt in enumerate(pts): BuilderUtils.CalculateDirectionsAtPoint(pt,shape.grid,self.winRad) if conf and self.featFactory: BuilderUtils.AssignMolFeatsToPoints(pts,conf.GetOwningMol(),self.featFactory,self.winRad) shape.skelPts=pts def CombineSubshapes(self,subshape1,subshape2,operation=SubshapeCombineOperations.UNION): import copy cs = copy.deepcopy(subshape1) if operation==SubshapeCombineOperations.UNION: cs.grid |= subshape2.grid elif operation==SubshapeCombineOperations.SUM: cs.grid += subshape2.grid elif operation==SubshapeCombineOperations.INTERSECT: cs.grid &= subshape2.grid else: raise ValueError('bad combination operation') return cs if __name__=='__main__': from rdkit.Chem import AllChem,ChemicalFeatures from rdkit.Chem.PyMol import MolViewer #cmpd = Chem.MolFromSmiles('CCCc1cc(C(=O)O)ccc1') #cmpd = Chem.AddHs(cmpd) if 1: cmpd = Chem.MolFromSmiles('C1=CC=C1C#CC1=CC=C1') cmpd = Chem.AddHs(cmpd) AllChem.EmbedMolecule(cmpd) AllChem.UFFOptimizeMolecule(cmpd) AllChem.CanonicalizeMol(cmpd) print >>file('testmol.mol','w+'),Chem.MolToMolBlock(cmpd) else: cmpd = Chem.MolFromMolFile('testmol.mol') builder=SubshapeBuilder() if 1: shape=builder.GenerateSubshapeShape(cmpd) v = MolViewer() if 1: import tempfile tmpFile = tempfile.mktemp('.grd') v.server.deleteAll() Geometry.WriteGridToFile(shape.grid,tmpFile) time.sleep(1) v.ShowMol(cmpd,name='testMol',showOnly=True) v.server.loadSurface(tmpFile,'testGrid','',2.5) v.server.resetCGO('*') cPickle.dump(shape,file('subshape.pkl','w+')) for i,pt in enumerate(shape.skelPts): v.server.sphere(tuple(pt.location),.5,(1,0,1),'Pt-%d'%i) if not hasattr(pt,'shapeDirs'): continue momBeg = pt.location-pt.shapeDirs[0] momEnd = pt.location+pt.shapeDirs[0] v.server.cylinder(tuple(momBeg),tuple(momEnd),.1,(1,0,1),'v-%d'%i)
{ "repo_name": "strets123/rdkit", "path": "rdkit/Chem/Subshape/SubshapeBuilder.py", "copies": "3", "size": "4317", "license": "bsd-3-clause", "hash": 1608845512702571000, "line_mean": 34.3852459016, "line_max": 95, "alpha_frac": 0.6847347695, "autogenerated": false, "ratio": 3.1373546511627906, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.532208942066279, "avg_score": null, "num_lines": null }
from rdkit import Chem,Geometry from rdkit.Chem import AllChem from rdkit.Chem.Subshape import SubshapeObjects from rdkit.Chem.Subshape import BuilderUtils import time,cPickle #----------------------------------------------------------------------------- class SubshapeCombineOperations(object): UNION=0 SUM=1 INTERSECT=2 #----------------------------------------------------------------------------- class SubshapeBuilder(object): gridDims=(20,15,10) gridSpacing=0.5 winRad=3.0 nbrCount=7 terminalPtRadScale=0.75 fraction=0.25 stepSize=1.0 featFactory=None def SampleSubshape(self,subshape1,newSpacing): ogrid=subshape1.grid rgrid = Geometry.UniformGrid3D(self.gridDims[0],self.gridDims[1],self.gridDims[2], newSpacing) for idx in range(rgrid.GetSize()): l = rgrid.GetGridPointLoc(idx) v = ogrid.GetValPoint(l) rgrid.SetVal(idx,v) res = SubshapeObjects.ShapeWithSkeleton() res.grid = rgrid return res; def GenerateSubshapeShape(self,cmpd,confId=-1,addSkeleton=True,**kwargs): shape = SubshapeObjects.ShapeWithSkeleton() shape.grid=Geometry.UniformGrid3D(self.gridDims[0],self.gridDims[1],self.gridDims[2], self.gridSpacing) AllChem.EncodeShape(cmpd,shape.grid,ignoreHs=False,confId=confId) if addSkeleton: conf = cmpd.GetConformer(confId) self.GenerateSubshapeSkeleton(shape,conf,kwargs) return shape def __call__(self,cmpd,**kwargs): return self.GenerateSubshapeShape(cmpd,**kwargs) def GenerateSubshapeSkeleton(self,shape,conf=None,terminalPtsOnly=False,skelFromConf=True): if conf and skelFromConf: pts = BuilderUtils.FindTerminalPtsFromConformer(conf,self.winRad,self.nbrCount) else: pts = BuilderUtils.FindTerminalPtsFromShape(shape,self.winRad,self.fraction) pts = BuilderUtils.ClusterTerminalPts(pts,self.winRad,self.terminalPtRadScale) BuilderUtils.ExpandTerminalPts(shape,pts,self.winRad) if len(pts)<3: raise ValueError,'only found %d terminals, need at least 3'%len(pts) if not terminalPtsOnly: pts = BuilderUtils.AppendSkeletonPoints(shape.grid,pts,self.winRad,self.stepSize) for i,pt in enumerate(pts): BuilderUtils.CalculateDirectionsAtPoint(pt,shape.grid,self.winRad) if conf and self.featFactory: BuilderUtils.AssignMolFeatsToPoints(pts,conf.GetOwningMol(),self.featFactory,self.winRad) shape.skelPts=pts def CombineSubshapes(self,subshape1,subshape2,operation=SubshapeCombineOperations.UNION): import copy cs = copy.deepcopy(subshape1) if operation==SubshapeCombineOperations.UNION: cs.grid |= subshape2.grid elif operation==SubshapeCombineOperations.SUM: cs.grid += subshape2.grid elif operation==SubshapeCombineOperations.INTERSECT: cs.grid &= subshape2.grid else: raise ValueError,'bad combination operation' return cs if __name__=='__main__': from rdkit.Chem import AllChem,ChemicalFeatures from rdkit.Chem.PyMol import MolViewer #cmpd = Chem.MolFromSmiles('CCCc1cc(C(=O)O)ccc1') #cmpd = Chem.AddHs(cmpd) if 1: cmpd = Chem.MolFromSmiles('C1=CC=C1C#CC1=CC=C1') cmpd = Chem.AddHs(cmpd) AllChem.EmbedMolecule(cmpd) AllChem.UFFOptimizeMolecule(cmpd) AllChem.CanonicalizeMol(cmpd) print >>file('testmol.mol','w+'),Chem.MolToMolBlock(cmpd) else: cmpd = Chem.MolFromMolFile('testmol.mol') builder=SubshapeBuilder() if 1: shape=builder.GenerateSubshapeShape(cmpd) v = MolViewer() if 1: import tempfile tmpFile = tempfile.mktemp('.grd') v.server.deleteAll() Geometry.WriteGridToFile(shape.grid,tmpFile) time.sleep(1) v.ShowMol(cmpd,name='testMol',showOnly=True) v.server.loadSurface(tmpFile,'testGrid','',2.5) v.server.resetCGO('*') cPickle.dump(shape,file('subshape.pkl','w+')) for i,pt in enumerate(shape.skelPts): v.server.sphere(tuple(pt.location),.5,(1,0,1),'Pt-%d'%i) if not hasattr(pt,'shapeDirs'): continue momBeg = pt.location-pt.shapeDirs[0] momEnd = pt.location+pt.shapeDirs[0] v.server.cylinder(tuple(momBeg),tuple(momEnd),.1,(1,0,1),'v-%d'%i)
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Subshape/SubshapeBuilder.py", "copies": "2", "size": "4287", "license": "bsd-3-clause", "hash": 61420677803268220, "line_mean": 34.4297520661, "line_max": 95, "alpha_frac": 0.6841614182, "autogenerated": false, "ratio": 3.1314828341855367, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4815644252385537, "avg_score": null, "num_lines": null }
from rdkit import Chem from rdkit import Geometry class SkeletonPoint(object): location = None shapeMoments = None shapeDirs = None molFeatures = None featmapFeatures = None fracVol = 0.0 def __init__(self, *args, **kwargs): self._initMemberData() self.location = kwargs.get('location', None) def _initMemberData(self): self.shapeMoments = (0.0, ) * 3 self.shapeDirs = [None] * 3 self.molFeatures = [] self.featmapFeatures = [] class ShapeWithSkeleton(object): grid = None skelPts = None def __init__(self, *args, **kwargs): self._initMemberData() def _initMemberData(self): self.skelPts = [] class SubshapeShape(object): shapes = None # a list of ShapeWithSkeleton objects at multiple resolutions (low to high) featMap = None keyFeat = None def __init__(self, *args, **kwargs): self._initMemberData() def _initMemberData(self): self.shapes = [] def _displaySubshapeSkelPt(viewer, skelPt, cgoNm, color): viewer.server.sphere(tuple(skelPt.location), .5, color, cgoNm) if hasattr(skelPt, 'shapeDirs'): momBeg = skelPt.location - skelPt.shapeDirs[0] momEnd = skelPt.location + skelPt.shapeDirs[0] viewer.server.cylinder(tuple(momBeg), tuple(momEnd), .1, color, cgoNm) def DisplaySubshapeSkeleton(viewer, shape, name, color=(1, 0, 1), colorByOrder=False): orderColors = ((1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1), (0, 1, 1)) cgoNm = '%s-skeleton' % name viewer.server.resetCGO(cgoNm) for i, pt in enumerate(shape.skelPts): if colorByOrder: color = orderColors[i % len(orderColors)] _displaySubshapeSkelPt(viewer, pt, cgoNm, color) def DisplaySubshape(viewer, shape, name, showSkelPts=True, color=(1, 0, 1)): from rdkit import Geometry import os, tempfile fName = tempfile.mktemp('.grd') Geometry.WriteGridToFile(shape.grid, fName) viewer.server.loadSurface(fName, name, '', 2.5) if showSkelPts: DisplaySubshapeSkeleton(viewer, shape, name, color) # On Windows, the file cannot be deleted if the viewer still has the file open. # Pause for a moment, to give the viewer a chance, then try again. try: os.unlink(fName) except Exception: import time time.sleep(.5) try: os.unlink(fName) except Exception: # Fall back to the default of letting the system clean up the temporary directory. pass
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Subshape/SubshapeObjects.py", "copies": "1", "size": "2462", "license": "bsd-3-clause", "hash": -8598063768161824000, "line_mean": 26.6629213483, "line_max": 92, "alpha_frac": 0.6762794476, "autogenerated": false, "ratio": 3.0890840652446676, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42653635128446676, "avg_score": null, "num_lines": null }
from rdkit import RDConfig import unittest from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem.Subshape import SubshapeBuilder, SubshapeObjects, SubshapeAligner from rdkit.six.moves import cPickle import copy, sys, os class TestCase(unittest.TestCase): def setUp(self): pass def test1(self): suppl = Chem.SDMolSupplier( os.path.join(RDConfig.RDCodeDir, 'Chem', 'Subshape', 'test_data/5ht3ligs.sdf')) builder = SubshapeBuilder.SubshapeBuilder() builder.gridDims = (20., 20., 10) builder.gridSpacing = 0.5 builder.winRad = 4. ms = [] shapes = [] for m in suppl: m = Chem.AddHs(m, addCoords=True) AllChem.CanonicalizeConformer(m.GetConformer()) ms.append(m) shape = builder(m, terminalPtsOnly=True) shapes.append(shape) self.assertTrue(len(ms) == 4) self.assertTrue(len(shapes) == 4) self.assertTrue([len(x.skelPts) for x in shapes] == [5, 5, 5, 5]) refShape = builder.GenerateSubshapeShape(ms[0]) self.assertTrue(len(refShape.skelPts) == 15) aligner = SubshapeAligner.SubshapeAligner() aligner.shapeDistTol = .30 algStore = [] for i, s1 in enumerate(shapes): if not i or not s1: algStore.append([]) continue m1 = ms[i] alignments = aligner.GetSubshapeAlignments(ms[0], refShape, m1, s1, builder) algStore.append(alignments) self.assertEqual([len(x) for x in algStore], [0, 2, 39, 0]) algStore = [] for i, s1 in enumerate(shapes): if not i or not s1: algStore.append([]) continue m1 = ms[i] alignments = list(aligner(ms[0], refShape, m1, s1, builder)) algStore.append(alignments) self.assertTrue([len(x) for x in algStore] == [0, 2, 39, 0]) pruned = [] for i, mi in enumerate(ms): alignments = algStore[i] pruned.append(SubshapeAligner.ClusterAlignments(mi, alignments, builder, neighborTol=0.15)) self.assertTrue([len(x) for x in pruned] == [0, 2, 29, 0]) if __name__ == '__main__': unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Subshape/UnitTestSubshape.py", "copies": "1", "size": "2327", "license": "bsd-3-clause", "hash": 1802195945114106400, "line_mean": 28.0875, "line_max": 97, "alpha_frac": 0.6506231199, "autogenerated": false, "ratio": 3.0985352862849536, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9203420520443628, "avg_score": 0.009147577148265145, "num_lines": 80 }
from rdkit import RDConfig import unittest from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem.Subshape import SubshapeBuilder,SubshapeObjects,SubshapeAligner import cPickle,copy,sys,os class TestCase(unittest.TestCase): def setUp(self): pass def test1(self): suppl = Chem.SDMolSupplier(os.path.join(RDConfig.RDCodeDir,'Chem','Subshape', 'test_data/5ht3ligs.sdf')) builder = SubshapeBuilder.SubshapeBuilder() builder.gridDims=(20.,20.,10) builder.gridSpacing=0.5 builder.winRad=4. ms = [] shapes=[] for m in suppl: m = Chem.AddHs(m,addCoords=True) AllChem.CanonicalizeConformer(m.GetConformer()) ms.append(m) shape = builder(m,terminalPtsOnly=True) shapes.append(shape) self.failUnless(len(ms)==4) self.failUnless(len(shapes)==4) self.failUnless([len(x.skelPts) for x in shapes] == [5,5,5,5]) refShape = builder.GenerateSubshapeShape(ms[0]) self.failUnless(len(refShape.skelPts)==15) aligner = SubshapeAligner.SubshapeAligner() aligner.shapeDistTol=.30 algStore = [] for i,s1 in enumerate(shapes): if not i or not s1: algStore.append([]) continue m1 = ms[i] alignments = aligner.GetSubshapeAlignments(ms[0],refShape,m1,s1,builder) algStore.append(alignments) self.failUnlessEqual([len(x) for x in algStore],[0,2,39,0]) algStore = [] for i,s1 in enumerate(shapes): if not i or not s1: algStore.append([]) continue m1 = ms[i] alignments = list(aligner(ms[0],refShape,m1,s1,builder)) algStore.append(alignments) self.failUnless([len(x) for x in algStore] == [0,2,39,0]) pruned=[] for i,mi in enumerate(ms): alignments=algStore[i] pruned.append(SubshapeAligner.ClusterAlignments(mi,alignments,builder, neighborTol=0.15)) self.failUnless([len(x) for x in pruned] == [0,2,29,0]) if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Subshape/UnitTestSubshape.py", "copies": "2", "size": "2353", "license": "bsd-3-clause", "hash": -8763066827853777000, "line_mean": 26.6823529412, "line_max": 81, "alpha_frac": 0.635359116, "autogenerated": false, "ratio": 3.1926729986431477, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48280321146431476, "avg_score": null, "num_lines": null }
import sys from rdkit import Chem class FastSDMolSupplier(object): """ A wrapper around an SDMolSupplier that precomputes and stores molecular indices (via text processing) to allow quick length calculations and random access. NOTE that this class needs to have the entire SD data in memory, so it's probably not particularly useful with large files. """ suppl=None data=None sanitize=True def __init__(self,fileN=None,data=None,sanitize=True,removeHs=True): if fileN: data = open(fileN,'r').read() self.sanitize=sanitize self.removeHs=removeHs if data: data = data.replace('\r\n','\n') self.init(data) def init(self,data,recogTxt='$$$$\n'): if not data: raise ValueError,'no data' # FIX: it'd be nice to not be caching data locally like this, but it's the easiest # way to handle pickle support. self.data=data self.suppl = Chem.SDMolSupplier() self.suppl.SetData(data,sanitize=self.sanitize,removeHs=self.removeHs) self._pos = [0] p = 0 while 1: try: p = data.index(recogTxt,p+1) p+=len(recogTxt) except: break else: self._pos.append(p) self._pos.pop(-1) self.suppl._SetStreamIndices(self._pos) self._idx=0 def GetItemText(self,idx): startOfItem = self._pos[idx] if idx+1<len(self._pos): endOfItem = self._pos[idx+1] else: endOfItem = -1 return self.data[startOfItem:endOfItem] def reset(self): self.suppl.reset() self._idx=0 # ---------------------------------------------------------------- # support random access and an iterator interface: def __iter__(self): self.suppl.reset() return self def next(self): self._idx+=1 return self.suppl.next() def __len__(self): return len(self.suppl) def __getitem__(self,idx): return self.suppl[idx]
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/FastSDMolSupplier.py", "copies": "2", "size": "2187", "license": "bsd-3-clause", "hash": 987777521608486100, "line_mean": 25.6707317073, "line_max": 86, "alpha_frac": 0.6195701875, "autogenerated": false, "ratio": 3.438679245283019, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.505824943278302, "avg_score": null, "num_lines": null }
import unittest,subprocess,os from rdkit import RDConfig from rdkit.Dbase.DbConnection import DbConnect class TestCase(unittest.TestCase): def test1Create(self): p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', 'testData/bzr.smi')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') self.assertTrue(d[0][0]==10) conn = DbConnect('testData/bzr/AtomPairs.sqlt') d = conn.GetData('atompairs',fields='count(*)') self.assertTrue(d[0][0]==10) conn = DbConnect('testData/bzr/Descriptors.sqlt') d = conn.GetData('descriptors_v1',fields='count(*)') self.assertTrue(d[0][0]==10) conn = DbConnect('testData/bzr/Fingerprints.sqlt') d = conn.GetData('rdkitfps',fields='count(*)') self.assertTrue(d[0][0]==10) p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=sdf', '--doGobbi2D', 'testData/bzr.sdf')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') self.assertTrue(d[0][0]==163) conn = DbConnect('testData/bzr/AtomPairs.sqlt') d = conn.GetData('atompairs',fields='count(*)') self.assertTrue(d[0][0]==163) conn = DbConnect('testData/bzr/Descriptors.sqlt') d = conn.GetData('descriptors_v1',fields='count(*)') self.assertTrue(d[0][0]==163) conn = DbConnect('testData/bzr/Fingerprints.sqlt') d = conn.GetData('rdkitfps',fields='count(*)') self.assertTrue(d[0][0]==163) def test2_1SearchFPs(self): self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr','--molFormat=sdf', '--topN=5','--outF=testData/bzr/search.out','testData/bzr.sdf')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertTrue(len(lines)==163) splitLs=[x.strip().split(',') for x in lines] for line in splitLs: lbl = line[0] i=1 nbrs={} lastVal=1.0 while i<len(line): nbrs[line[i]]=line[i+1] self.assertTrue(float(line[i+1])<=lastVal) lastVal=float(line[i+1]) i+=2 self.assertTrue(lbl in nbrs) self.assertTrue(nbrs[lbl]=='1.000',nbrs[lbl]) os.unlink('testData/bzr/search.out') def test2_2SearchAtomPairs(self): self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr','--molFormat=sdf', '--topN=5','--outF=testData/bzr/search.out','--similarityType=AtomPairs', 'testData/bzr.sdf')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertTrue(len(lines)==163) splitLs=[x.strip().split(',') for x in lines] for line in splitLs: lbl = line[0] i=1 nbrs={} lastVal=1.0 while i<len(line): nbrs[line[i]]=line[i+1] self.assertTrue(float(line[i+1])<=lastVal) lastVal=float(line[i+1]) i+=2 self.assertTrue(lbl in nbrs) self.assertTrue(nbrs[lbl]=='1.000') os.unlink('testData/bzr/search.out') def test2_3SearchTorsions(self): self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr','--molFormat=sdf','--topN=5', '--outF=testData/bzr/search.out','--similarityType=TopologicalTorsions', 'testData/bzr.sdf')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertTrue(len(lines)==163) splitLs=[x.strip().split(',') for x in lines] for line in splitLs: lbl = line[0] i=1 nbrs={} lastVal=1.0 while i<len(line): nbrs[line[i]]=line[i+1] self.assertTrue(float(line[i+1])<=lastVal) lastVal=float(line[i+1]) i+=2 self.assertTrue(lbl in nbrs) self.assertTrue(nbrs[lbl]=='1.000') os.unlink('testData/bzr/search.out') def test2_4SearchProps(self): self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr', '--outF=testData/bzr/search.out','--query=activity<6.5')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertTrue(len(lines)==30) os.unlink('testData/bzr/search.out') p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr', '--outF=testData/bzr/search.out','--query=activity<6.5')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertTrue(len(lines)==30) os.unlink('testData/bzr/search.out') def test2_5SearchSmarts(self): p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr', '--outF=testData/bzr/search.out','--smarts=cncncc',)) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertEqual(len(lines),49) os.unlink('testData/bzr/search.out') if os.path.exists('/dev/null'): p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr', '--outF=/dev/null', '--smilesOut=testData/bzr/search.out', '--smarts=cncncc',)) else: p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr', '--outF=testData/crud.out', '--smilesOut=testData/bzr/search.out', '--smarts=cncncc',)) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertEqual(len(lines),49) os.unlink('testData/bzr/search.out') if os.path.exists('testData/crud.out'): os.unlink('testData/crud.out') p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr', '--outF=testData/bzr/search.out','--negate','--smarts=cncncc',)) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertEqual(len(lines),114) os.unlink('testData/bzr/search.out') def test2_6SearchBoth(self): p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr', '--outF=testData/bzr/search.out','--query=activity<6.5','--smarts=cncncc')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertEqual(len(lines),5) os.unlink('testData/bzr/search.out') p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr', '--outF=testData/bzr/search.out','--query=activity<6.5', '--smarts=cncncc','--negate')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertEqual(len(lines),25) os.unlink('testData/bzr/search.out') def test2_7SearchGobbi(self): self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr','--molFormat=sdf','--topN=5', '--outF=testData/bzr/search.out','--similarityType=Gobbi2D', 'testData/bzr.sdf')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertTrue(len(lines)==163) splitLs=[x.strip().split(',') for x in lines] for line in splitLs: lbl = line[0] i=1 nbrs={} lastVal=1.0 while i<len(line): nbrs[line[i]]=line[i+1] self.assertTrue(float(line[i+1])<=lastVal) lastVal=float(line[i+1]) i+=2 self.assertTrue(lbl in nbrs) self.assertTrue(nbrs[lbl]=='1.000') self.assertEqual(splitLs[0][0],'Adinazolam') self.assertEqual(splitLs[0][3],'alpha-hydroxytriazolam') self.assertEqual(splitLs[0][4],'0.631') os.unlink('testData/bzr/search.out') def test2_8SearchThresh(self): self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr','--molFormat=sdf', '--simThresh=0.7','--outF=testData/bzr/search.out','testData/bzr_q1.mol')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertTrue(len(lines)==1) splitL=lines[0].strip().split(',') splitL.pop(0) for i in range(0,len(splitL),2): v = float(splitL[i+1]) self.assertTrue(v>0.7) os.unlink('testData/bzr/search.out') def test4CreateOptions(self): if os.path.exists('testData/bzr/Compounds.sqlt'): os.unlink('testData/bzr/Compounds.sqlt') if os.path.exists('testData/bzr/AtomPairs.sqlt'): os.unlink('testData/bzr/AtomPairs.sqlt') if os.path.exists('testData/bzr/Descriptors.sqlt'): os.unlink('testData/bzr/Descriptors.sqlt') if os.path.exists('testData/bzr/Fingerprints.sqlt'): os.unlink('testData/bzr/Fingerprints.sqlt') p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', '--noExtras','--noSmiles', 'testData/bzr.smi')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertFalse(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') self.assertEqual(d[0][0],10) d = conn.GetData('molecules',fields='*') self.assertEqual(len(d),10) cns = [x.lower() for x in d.GetColumnNames()] self.assertFalse('smiles' in cns) conn=None d=None if os.path.exists('testData/bzr/Compounds.sqlt'): os.unlink('testData/bzr/Compounds.sqlt') if os.path.exists('testData/bzr/AtomPairs.sqlt'): os.unlink('testData/bzr/AtomPairs.sqlt') if os.path.exists('testData/bzr/Descriptors.sqlt'): os.unlink('testData/bzr/Descriptors.sqlt') if os.path.exists('testData/bzr/Fingerprints.sqlt'): os.unlink('testData/bzr/Fingerprints.sqlt') p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', '--noSmiles','--noFingerprints','--noLayeredFps','--noMorganFps','--noPairs','--noDescriptors', 'testData/bzr.smi')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertFalse(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') self.assertTrue(d[0][0]==10) d = conn.GetData('molecules',fields='*') self.assertTrue(len(d)==10) cns = [x.lower() for x in d.GetColumnNames()] self.assertFalse('smiles' in cns) d = None conn.KillCursor() conn = None p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', '--noProps','--noFingerprints','--noLayeredFps','--noMorganFps','--noPairs','--noDescriptors', 'testData/bzr.smi')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertFalse(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') self.assertEqual(d[0][0],10) d = conn.GetData('molecules',fields='*') self.assertEqual(len(d),10) cns = [x.lower() for x in d.GetColumnNames()] self.assertTrue('smiles' in cns) d = None conn.KillCursor() conn = None p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', '--noFingerprints','--noLayeredFps','--noMorganFps','--noPairs','--noDescriptors', '--maxRowsCached=4', 'testData/bzr.smi')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertFalse(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') self.assertEqual(d[0][0],10) d = conn.GetData('molecules',fields='*') self.assertEqual(len(d),10) cns = [x.lower() for x in d.GetColumnNames()] self.assertTrue('smiles' in cns) d = None conn.KillCursor() conn = None p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', '--noFingerprints', '--noPairs','--noDescriptors', '--maxRowsCached=4', 'testData/bzr.smi')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) def test5TestBackwardsCompat(self): if os.path.exists('testData/bzr/Compounds.sqlt'): os.unlink('testData/bzr/Compounds.sqlt') if os.path.exists('testData/bzr/AtomPairs.sqlt'): os.unlink('testData/bzr/AtomPairs.sqlt') if os.path.exists('testData/bzr/Descriptors.sqlt'): os.unlink('testData/bzr/Descriptors.sqlt') if os.path.exists('testData/bzr/Fingerprints.sqlt'): os.unlink('testData/bzr/Fingerprints.sqlt') p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr', '--noFingerprints','--noDescriptors', 'testData/bzr.sdf')) res=p.wait() self.assertFalse(res) p=None conn = DbConnect('testData/bzr/AtomPairs.sqlt') curs = conn.GetCursor() curs.execute('create table tmp as select compound_id,atompairfp,torsionfp from atompairs') p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr','--molFormat=sdf', '--topN=5','--outF=testData/bzr/search.out','--similarityType=AtomPairs', '--pairTableName=tmp', 'testData/bzr.sdf')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/search.out')) with open('testData/bzr/search.out','r') as inF: lines=inF.readlines() self.assertEqual(len(lines),163) splitLs=[x.strip().split(',') for x in lines] for line in splitLs: lbl = line[0] i=1 nbrs={} lastVal=1.0 while i<len(line): nbrs[line[i]]=line[i+1] self.assertTrue(float(line[i+1])<=lastVal) lastVal=float(line[i+1]) i+=2 self.assertTrue(lbl in nbrs) self.assertTrue(nbrs[lbl]=='1.000') os.unlink('testData/bzr/search.out') def test6Update(self): p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', 'testData/bzr.smi')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') self.assertEqual(d[0][0],10) conn = DbConnect('testData/bzr/AtomPairs.sqlt') d = conn.GetData('atompairs',fields='count(*)') self.assertEqual(d[0][0],10) conn = DbConnect('testData/bzr/Descriptors.sqlt') d = conn.GetData('descriptors_v1',fields='count(*)') self.assertEqual(d[0][0],10) conn = DbConnect('testData/bzr/Fingerprints.sqlt') d = conn.GetData('rdkitfps',fields='count(*)') self.assertEqual(d[0][0],10) d = None conn.KillCursor() p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', '--updateDb', 'testData/bzr.2.smi')) res=p.wait() self.assertFalse(res) p=None self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') self.assertEqual(d[0][0],20) conn = DbConnect('testData/bzr/AtomPairs.sqlt') d = conn.GetData('atompairs',fields='count(*)') self.assertEqual(d[0][0],20) conn = DbConnect('testData/bzr/Descriptors.sqlt') d = conn.GetData('descriptors_v1',fields='count(*)') self.assertEqual(d[0][0],20) conn = DbConnect('testData/bzr/Fingerprints.sqlt') d = conn.GetData('rdkitfps',fields='count(*)') self.assertEqual(d[0][0],20) if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "Projects/DbCLI/TestDbCLI.py", "copies": "1", "size": "21537", "license": "bsd-3-clause", "hash": -4108120497962908000, "line_mean": 36.3258232236, "line_max": 121, "alpha_frac": 0.6210242838, "autogenerated": false, "ratio": 3.1194959443800694, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9046570126531077, "avg_score": 0.03879002032979866, "num_lines": 577 }
from __future__ import print_function import unittest,os,gzip from rdkit.six.moves import cPickle #@UnresolvedImport #pylint: disable=F0401 from rdkit import Chem from rdkit import RDConfig from rdkit.Chem.AtomPairs import Pairs,Torsions,Utils class TestCase(unittest.TestCase): def setUp(self): self.testDataPath=os.path.join(RDConfig.RDCodeDir,'Chem','AtomPairs','test_data') inF = gzip.open(os.path.join(self.testDataPath,'mols1000.pkl.gz'),'rb') self.mols=cPickle.load(inF, encoding='bytes') def testPairsRegression(self): inF = gzip.open(os.path.join(self.testDataPath,'mols1000.aps.pkl.gz'),'rb') atomPairs = cPickle.load(inF, encoding='bytes') for i,m in enumerate(self.mols): ap = Pairs.GetAtomPairFingerprint(m) #if ap!=atomPairs[i]: # print Chem.MolToSmiles(m) # pd=ap.GetNonzeroElements() # rd=atomPairs[i].GetNonzeroElements() # for k,v in pd.iteritems(): # if rd.has_key(k): # if rd[k]!=v: print '>>>1',k,v,rd[k] # else: # print '>>>2',k,v # for k,v in rd.iteritems(): # if pd.has_key(k): # if pd[k]!=v: print '>>>3',k,v,pd[k] # else: # print '>>>4',k,v self.assertTrue(ap==atomPairs[i]) self.assertTrue(ap!=atomPairs[i-1]) def testTorsionsRegression(self): inF = gzip.open(os.path.join(self.testDataPath,'mols1000.tts.pkl.gz'),'rb') torsions = cPickle.load(inF, encoding='bytes') for i,m in enumerate(self.mols): tt = Torsions.GetTopologicalTorsionFingerprintAsIntVect(m) if tt!=torsions[i]: print(Chem.MolToSmiles(m)) pd=tt.GetNonzeroElements() rd=torsions[i].GetNonzeroElements() for k,v in pd.iteritems(): if rd.has_key(k): if rd[k]!=v: print('>>>1',k,v,rd[k]) else: print('>>>2',k,v) for k,v in rd.iteritems(): if pd.has_key(k): if pd[k]!=v: print('>>>3',k,v,pd[k]) else: print('>>>4',k,v) self.assertTrue(tt==torsions[i]) self.assertTrue(tt!=torsions[i-1]) def testGithub334(self): m1 = Chem.MolFromSmiles('N#C') self.assertEqual(Utils.NumPiElectrons(m1.GetAtomWithIdx(0)),2) self.assertEqual(Utils.NumPiElectrons(m1.GetAtomWithIdx(1)),2) m1 = Chem.MolFromSmiles('N#[CH]') self.assertEqual(Utils.NumPiElectrons(m1.GetAtomWithIdx(0)),2) self.assertEqual(Utils.NumPiElectrons(m1.GetAtomWithIdx(1)),2) if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/AtomPairs/UnitTestDescriptors.py", "copies": "4", "size": "2805", "license": "bsd-3-clause", "hash": -1137841260929632800, "line_mean": 34.0625, "line_max": 85, "alpha_frac": 0.6210338681, "autogenerated": false, "ratio": 2.8535096642929805, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.547454353239298, "avg_score": null, "num_lines": null }
from __future__ import print_function import doctest import unittest from rdkit import Chem, RDLogger from rdkit.VLib.NodeLib import SDSupply, SmartsMolFilter, SmartsRemover from rdkit.VLib.NodeLib import SmilesDupeFilter, SmilesOutput, SmilesSupply from rdkit.VLib.Supply import SupplyNode from rdkit.six import StringIO def load_tests(loader, tests, ignore): """ Add the Doctests from the module """ tests.addTests(doctest.DocTestSuite(SDSupply, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(SmartsMolFilter, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(SmartsRemover, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(SmilesDupeFilter, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(SmilesOutput, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(SmilesSupply, optionflags=doctest.ELLIPSIS)) # tests.addTests(doctest.DocTestSuite(DbMolSupply, optionflags=doctest.ELLIPSIS)) return tests class Test_NodeLib(unittest.TestCase): def tearDown(self): RDLogger.EnableLog('rdApp.error') def test_SmartsMolFilter(self): smis = ['C1CCC1', 'C1CCC1C=O', 'CCCC', 'CCC=O', 'CC(=O)C', 'CCN', 'NCCN', 'NCC=O'] mols = [Chem.MolFromSmiles(x) for x in smis] suppl = SupplyNode(contents=mols) self.assertEqual(len(list(suppl)), 8) smas = ['C=O', 'CN'] counts = [1, 2] filt = SmartsMolFilter.SmartsFilter(patterns=smas, counts=counts) filt.AddParent(suppl) self.assertEqual(len(list(filt)), 5) suppl.reset() filt.SetNegate(True) self.assertEqual(len(list(filt)), 3) smas = ['C=O', 'CN'] filt = SmartsMolFilter.SmartsFilter(patterns=smas) filt.AddParent(suppl) self.assertEqual(len(list(filt)), 6) self.assertRaises(ValueError, SmartsMolFilter.SmartsFilter, patterns=smas, counts=['notEnough', ]) RDLogger.DisableLog('rdApp.error') self.assertRaises(ValueError, SmartsMolFilter.SmartsFilter, patterns=['BadSmarts']) RDLogger.EnableLog('rdApp.error') def test_SmilesOutput(self): smis = ['C1CCC1', 'C1CC1', 'C=O', 'CCN'] mols = [Chem.MolFromSmiles(x) for x in smis] for i, mol in enumerate(mols, 100): mol.SetProp('ID', str(i)) suppl1 = SupplyNode(contents=mols) suppl2 = SupplyNode(contents='abcd') sio = StringIO() node = SmilesOutput.OutputNode(idField='ID', dest=sio, delim=', ') node.AddParent(suppl1) node.AddParent(suppl2) list(node) self.assertEqual(sio.getvalue(), '100, C1CCC1, a\n101, C1CC1, b\n102, C=O, c\n103, CCN, d\n') def test_SmartsRemover(self): salts = ['[Cl;H1&X1,-]', '[Na+]', '[O;H2,H1&-,X0&-2]', 'BadSmarts'] RDLogger.DisableLog('rdApp.error') self.assertRaises(ValueError, SmartsRemover.SmartsRemover, patterns=salts) RDLogger.EnableLog('rdApp.error') def test_SmilesDupeFilter(self): smis = ['C1CCC1', 'CCCC', 'CCCC', 'C1CCC1'] mols = [Chem.MolFromSmiles(x) for x in smis] suppl = SupplyNode(contents=mols) self.assertEqual(len(list(suppl)), 4) dupFilter = SmilesDupeFilter.DupeFilter() dupFilter.AddParent(suppl) self.assertEqual(len(list(dupFilter)), 2) if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/VLib/NodeLib/UnitTestNodeLib.py", "copies": "4", "size": "3541", "license": "bsd-3-clause", "hash": -8974093525175688000, "line_mean": 34.0594059406, "line_max": 97, "alpha_frac": 0.7026263767, "autogenerated": false, "ratio": 2.9706375838926173, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00525640066029321, "num_lines": 101 }
from __future__ import print_function import doctest import unittest from rdkit.VLib import Node, Filter, Output, Supply, Transform from rdkit.six import StringIO def load_tests(loader, tests, ignore): """ Add the Doctests from the module """ tests.addTests(doctest.DocTestSuite(Filter, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(Node, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(Output, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(Supply, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(Transform, optionflags=doctest.ELLIPSIS)) return tests class Test_VLib(unittest.TestCase): def test_SupplyNode(self): supplier = Supply.SupplyNode() self.assertEqual(supplier._contents, []) supplier = Supply.SupplyNode(contents=[1, 2, 3]) self.assertRaises(ValueError, supplier.AddParent, None) def test_FilterNode(self): filt = Filter.FilterNode(func=lambda a, b: a + b < 5) suppl1 = Supply.SupplyNode(contents=[1, 2, 3, 3]) suppl2 = Supply.SupplyNode(contents=[1, 2, 3, 1]) filt.AddParent(suppl1) filt.AddParent(suppl2) self.assertEqual([x for x in filt], [(1, 1), (2, 2), (3, 1)]) filt.reset() self.assertEqual(filt.Negate(), False) filt.SetNegate(True) self.assertEqual(filt.Negate(), True) self.assertEqual([x for x in filt], [(3, 3), ]) filt.Destroy() def test_OutputNode(self): supplier1 = Supply.SupplyNode(contents=[1, 2, 3]) supplier2 = Supply.SupplyNode(contents=['a', 'b', 'c']) sio = StringIO() node = Output.OutputNode(dest=sio, strFunc=lambda x: '{0[0]}-{0[1]} '.format(x)) node.AddParent(supplier1) node.AddParent(supplier2) result = list(s for s in node) self.assertEqual(result, [(1, 'a'), (2, 'b'), (3, 'c')]) self.assertEqual(sio.getvalue(), '1-a 2-b 3-c ') sio = StringIO() node = Output.OutputNode(dest=sio) node.AddParent(supplier1) result = list(s for s in node) self.assertEqual(result, [1, 2, 3]) self.assertEqual(sio.getvalue(), '123') def test_VLibNode(self): def setupNodes(): p1 = Node.VLibNode() p2 = Node.VLibNode() c1 = Node.VLibNode() c2 = Node.VLibNode() p1.AddChild(c1) p2.AddChild(c1) p2.AddChild(c2) return p1, p2, c1, c2 p1, p2, c1, c2 = setupNodes() # p1 -> c1 # p2 -> c1 # p2 -> c2 self.assertEqual(len(c1.GetParents()), 2) self.assertEqual(len(c2.GetParents()), 1) self.assertEqual(len(p1.GetChildren()), 1) self.assertEqual(len(p2.GetChildren()), 2) p1.Destroy() # p1 # p2 -> c1 # p2 -> c2 self.assertEqual(len(c1.GetParents()), 1) self.assertEqual(len(c2.GetParents()), 1) self.assertEqual(len(p1.GetChildren()), 0) self.assertEqual(len(p2.GetChildren()), 2) p1, p2, c1, c2 = setupNodes() p1.Destroy(propagateDown=True) # p1, c1 # p2 -> c2 self.assertEqual(len(c1.GetParents()), 0) self.assertEqual(len(c2.GetParents()), 1) self.assertEqual(len(p1.GetChildren()), 0) self.assertEqual(len(p2.GetChildren()), 1) p1, p2, c1, c2 = setupNodes() p1.Destroy(propagateUp=True) # p1 # p2 -> c1 # p2 -> c2 self.assertEqual(len(c1.GetParents()), 1) self.assertEqual(len(c2.GetParents()), 1) self.assertEqual(len(p1.GetChildren()), 0) self.assertEqual(len(p2.GetChildren()), 2) p1, p2, c1, c2 = setupNodes() c1.Destroy(propagateUp=True) # p1, c1, p2, c2 self.assertEqual(len(c1.GetParents()), 0) self.assertEqual(len(c2.GetParents()), 0) self.assertEqual(len(p1.GetChildren()), 0) self.assertEqual(len(p2.GetChildren()), 0) p1, p2, c1, c2 = setupNodes() p1.Destroy(propagateDown=True) # p1, c1 # p2 -> c2 self.assertEqual(len(c1.GetParents()), 0) self.assertEqual(len(c2.GetParents()), 1) self.assertEqual(len(p1.GetChildren()), 0) self.assertEqual(len(p2.GetChildren()), 1) p1.Destroy(propagateDown=True) # p1, c1 # p2 -> c2 self.assertEqual(len(c1.GetParents()), 0) self.assertEqual(len(c2.GetParents()), 1) self.assertEqual(len(p1.GetChildren()), 0) self.assertEqual(len(p2.GetChildren()), 1) if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/VLib/UnitTestVLib.py", "copies": "4", "size": "4576", "license": "bsd-3-clause", "hash": -5492795978610100000, "line_mean": 30.1292517007, "line_max": 84, "alpha_frac": 0.6479458042, "autogenerated": false, "ratio": 2.9811074918566773, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5629053296056677, "avg_score": null, "num_lines": null }
_version = "0.13.0" _usage=""" SearchDb [optional arguments] <sdfilename> The sd filename argument can be either an SD file or an MDL mol file. NOTES: - The property names may have been altered on loading the database. Any non-alphanumeric character in a property name will be replaced with '_'. e.g."Gold.Goldscore.Constraint.Score" becomes "Gold_Goldscore_Constraint_Score". - Property names are not case sensitive in the database. """ from rdkit import RDConfig from rdkit.Dbase.DbConnection import DbConnect from rdkit.RDLogger import logger logger=logger() import zlib from rdkit import Chem from rdkit.Chem.MolDb.FingerprintUtils import supportedSimilarityMethods,BuildSigFactory,DepickleFP,LayeredOptions from rdkit.Chem.MolDb import FingerprintUtils from rdkit import DataStructs def GetNeighborLists(probes,topN,pool, simMetric=DataStructs.DiceSimilarity, silent=False): probeFps = [x[1] for x in probes] validProbes = [x for x in range(len(probeFps)) if probeFps[x] is not None] validFps=[probeFps[x] for x in validProbes] from rdkit.DataStructs.TopNContainer import TopNContainer nbrLists = [TopNContainer(topN) for x in range(len(probeFps))] nDone=0 for nm,fp in pool: nDone+=1 if not silent and not nDone%1000: logger.info(' searched %d rows'%nDone) if(simMetric==DataStructs.DiceSimilarity): scores = DataStructs.BulkDiceSimilarity(fp,validFps) for i,score in enumerate(scores): nbrLists[validProbes[i]].Insert(score,nm) elif(simMetric==DataStructs.TanimotoSimilarity): scores = DataStructs.BulkTanimotoSimilarity(fp,validFps) for i,score in enumerate(scores): nbrLists[validProbes[i]].Insert(score,nm) else: for i in range(len(probeFps)): pfp = probeFps[i] if pfp is not None: score = simMetric(probeFps[i],fp) nbrLists[i].Insert(score,nm) return nbrLists def GetMolsFromSmilesFile(dataFilename,errFile,nameProp): dataFile=file(dataFilename,'r') for idx,line in enumerate(dataFile): try: smi,nm = line.strip().split(' ') except: continue try: m = Chem.MolFromSmiles(smi) except: m=None if not m: if errfile: print >>errFile,idx,nm,smi continue yield (nm,smi,m) def GetMolsFromSDFile(dataFilename,errFile,nameProp): suppl = Chem.SDMolSupplier(dataFilename) for idx,m in enumerate(suppl): if not m: if errFile: if hasattr(suppl,'GetItemText'): d = suppl.GetItemText(idx) errFile.write(d) else: logger.warning('full error file support not complete') continue smi = Chem.MolToSmiles(m,True) if m.HasProp(nameProp): nm = m.GetProp(nameProp) if not nm: logger.warning('molecule found with empty name property') else: nm = 'Mol_%d'%(idx+1) yield nm,smi,m def RunSearch(options,queryFilename): global sigFactory if options.similarityType=='AtomPairs': fpBuilder=FingerprintUtils.BuildAtomPairFP simMetric=DataStructs.DiceSimilarity dbName = os.path.join(options.dbDir,options.pairDbName) fpTableName = options.pairTableName fpColName = options.pairColName elif options.similarityType=='TopologicalTorsions': fpBuilder=FingerprintUtils.BuildTorsionsFP simMetric=DataStructs.DiceSimilarity dbName = os.path.join(options.dbDir,options.torsionsDbName) fpTableName = options.torsionsTableName fpColName = options.torsionsColName elif options.similarityType=='RDK': fpBuilder=FingerprintUtils.BuildRDKitFP simMetric=DataStructs.FingerprintSimilarity dbName = os.path.join(options.dbDir,options.fpDbName) fpTableName = options.fpTableName if not options.fpColName: options.fpColName='rdkfp' fpColName = options.fpColName elif options.similarityType=='Pharm2D': fpBuilder=FingerprintUtils.BuildPharm2DFP simMetric=DataStructs.DiceSimilarity dbName = os.path.join(options.dbDir,options.fpDbName) fpTableName = options.pharm2DTableName if not options.fpColName: options.fpColName='pharm2dfp' fpColName = options.fpColName FingerprintUtils.sigFactory = BuildSigFactory(options) elif options.similarityType=='Gobbi2D': from rdkit.Chem.Pharm2D import Gobbi_Pharm2D fpBuilder=FingerprintUtils.BuildPharm2DFP simMetric=DataStructs.TanimotoSimilarity dbName = os.path.join(options.dbDir,options.fpDbName) fpTableName = options.gobbi2DTableName if not options.fpColName: options.fpColName='gobbi2dfp' fpColName = options.fpColName FingerprintUtils.sigFactory = Gobbi_Pharm2D.factory elif options.similarityType=='Morgan': fpBuilder=FingerprintUtils.BuildMorganFP simMetric=DataStructs.DiceSimilarity dbName = os.path.join(options.dbDir,options.morganFpDbName) fpTableName = options.morganFpTableName fpColName = options.morganFpColName if options.smilesQuery: mol=Chem.MolFromSmiles(options.smilesQuery) if not mol: logger.error('could not build query molecule from smiles "%s"'%options.smilesQuery) sys.exit(-1) options.queryMol = mol elif options.smartsQuery: mol=Chem.MolFromSmarts(options.smartsQuery) if not mol: logger.error('could not build query molecule from smarts "%s"'%options.smartsQuery) sys.exit(-1) options.queryMol = mol if options.outF=='-': outF=sys.stdout elif options.outF=='': outF=None else: outF = file(options.outF,'w+') molsOut=False if options.sdfOut: molsOut=True if options.sdfOut=='-': sdfOut=sys.stdout else: sdfOut = file(options.sdfOut,'w+') else: sdfOut=None if options.smilesOut: molsOut=True if options.smilesOut=='-': smilesOut=sys.stdout else: smilesOut = file(options.smilesOut,'w+') else: smilesOut=None if queryFilename: try: tmpF = file(queryFilename,'r') except IOError: logger.error('could not open query file %s'%queryFilename) sys.exit(1) if options.molFormat=='smiles': func=GetMolsFromSmilesFile elif options.molFormat=='sdf': func=GetMolsFromSDFile if not options.silent: msg='Reading query molecules' if fpBuilder: msg+=' and generating fingerprints' logger.info(msg) probes=[] i=0 nms=[] for nm,smi,mol in func(queryFilename,None,options.nameProp): i+=1 nms.append(nm) if not mol: logger.error('query molecule %d could not be built'%(i)) probes.append((None,None)) continue if fpBuilder: probes.append((mol,fpBuilder(mol))) else: probes.append((mol,None)) if not options.silent and not i%1000: logger.info(" done %d"%i) else: probes=None conn=None idName = options.molIdName ids=None names=None molDbName = os.path.join(options.dbDir,options.molDbName) molIdName = options.molIdName mConn = DbConnect(molDbName) cns = [(x.lower(),y) for x,y in mConn.GetColumnNamesAndTypes('molecules')] idCol,idTyp=cns[0] if options.propQuery or options.queryMol: conn = DbConnect(molDbName) curs = conn.GetCursor() if options.queryMol: if not options.silent: logger.info('Doing substructure query') if options.propQuery: where='where %s'%options.propQuery else: where='' if not options.silent: curs.execute('select count(*) from molecules %(where)s'%locals()) nToDo = curs.fetchone()[0] join='' doSubstructFPs=False fpDbName = os.path.join(options.dbDir,options.fpDbName) if os.path.exists(fpDbName) and not options.negateQuery : curs.execute("attach database '%s' as fpdb"%(fpDbName)) try: curs.execute('select * from fpdb.%s limit 1'%options.layeredTableName) except: pass else: doSubstructFPs=True join = 'join fpdb.%s using (%s)'%(options.layeredTableName,idCol) query = LayeredOptions.GetQueryText(options.queryMol) if query: if not where: where='where' else: where += ' and' where += ' '+query cmd = 'select %(idCol)s,molpkl from molecules %(join)s %(where)s'%locals() curs.execute(cmd) row=curs.fetchone() nDone=0 ids=[] while row: id,molpkl = row if not options.zipMols: m = Chem.Mol(str(molpkl)) else: m = Chem.Mol(zlib.decompress(str(molpkl))) matched=m.HasSubstructMatch(options.queryMol) if options.negateQuery: matched = not matched if matched: ids.append(id) nDone+=1 if not options.silent and not nDone%500: if not doSubstructFPs: logger.info(' searched %d (of %d) molecules; %d hits so far'%(nDone,nToDo,len(ids))) else: logger.info(' searched through %d molecules; %d hits so far'%(nDone,len(ids))) row=curs.fetchone() if not options.silent and doSubstructFPs and nToDo: nFiltered = nToDo-nDone logger.info(' Fingerprint screenout rate: %d of %d (%%%.2f)'%(nFiltered,nToDo,100.*nFiltered/nToDo)) elif options.propQuery: if not options.silent: logger.info('Doing property query') propQuery=options.propQuery.split(';')[0] curs.execute('select %(idCol)s from molecules where %(propQuery)s'%locals()) ids = [x[0] for x in curs.fetchall()] if not options.silent: logger.info('Found %d molecules matching the query'%(len(ids))) t1=time.time() if probes: if not options.silent: logger.info('Finding Neighbors') conn = DbConnect(dbName) cns = conn.GetColumnNames(fpTableName) curs = conn.GetCursor() if ids: ids = [(x,) for x in ids] curs.execute('create temporary table _tmpTbl (%(idCol)s %(idTyp)s)'%locals()) curs.executemany('insert into _tmpTbl values (?)',ids) join='join _tmpTbl using (%(idCol)s)'%locals() else: join='' if cns[0].lower() != idCol.lower(): # backwards compatibility to the days when mol tables had a guid and # the fps tables did not: curs.execute("attach database '%(molDbName)s' as mols"%locals()) curs.execute(""" select %(idCol)s,%(fpColName)s from %(fpTableName)s join (select %(idCol)s,%(molIdName)s from mols.molecules %(join)s) using (%(molIdName)s) """%(locals())) else: curs.execute('select %(idCol)s,%(fpColName)s from %(fpTableName)s %(join)s'%locals()) def poolFromCurs(curs,similarityMethod): row = curs.fetchone() while row: id,pkl = row fp = DepickleFP(str(pkl),similarityMethod) yield (id,fp) row = curs.fetchone() topNLists = GetNeighborLists(probes,options.topN,poolFromCurs(curs,options.similarityType), simMetric=simMetric) uniqIds=set() nbrLists = {} for i,nm in enumerate(nms): topNLists[i].reverse() scores=topNLists[i].GetPts() nbrNames = topNLists[i].GetExtras() nbrs = [] for j,nbrGuid in enumerate(nbrNames): if nbrGuid is None: break else: uniqIds.add(nbrGuid) nbrs.append((nbrGuid,scores[j])) nbrLists[(i,nm)] = nbrs t2=time.time() if not options.silent: logger.info('The search took %.1f seconds'%(t2-t1)) if not options.silent: logger.info('Creating output') curs = mConn.GetCursor() ids = list(uniqIds) ids = [(x,) for x in ids] curs.execute('create temporary table _tmpTbl (%(idCol)s %(idTyp)s)'%locals()) curs.executemany('insert into _tmpTbl values (?)',ids) curs.execute('select %(idCol)s,%(molIdName)s from molecules join _tmpTbl using (%(idCol)s)'%locals()) nmDict={} for guid,id in curs.fetchall(): nmDict[guid]=str(id) ks = nbrLists.keys() ks.sort() if not options.transpose: for i,nm in ks: nbrs= nbrLists[(i,nm)] nbrTxt=options.outputDelim.join([nm]+['%s%s%.3f'%(nmDict[id],options.outputDelim,score) for id,score in nbrs]) if outF: print >>outF,nbrTxt else: labels = ['%s%sSimilarity'%(x[1],options.outputDelim) for x in ks] if outF: print >>outF,options.outputDelim.join(labels) for i in range(options.topN): outL = [] for idx,nm in ks: nbr = nbrLists[(idx,nm)][i] outL.append(nmDict[nbr[0]]) outL.append('%.3f'%nbr[1]) if outF: print >>outF,options.outputDelim.join(outL) else: if not options.silent: logger.info('Creating output') curs = mConn.GetCursor() ids = [(x,) for x in set(ids)] curs.execute('create temporary table _tmpTbl (%(idCol)s %(idTyp)s)'%locals()) curs.executemany('insert into _tmpTbl values (?)',ids) molIdName = options.molIdName curs.execute('select %(idCol)s,%(molIdName)s from molecules join _tmpTbl using (%(idCol)s)'%locals()) nmDict={} for guid,id in curs.fetchall(): nmDict[guid]=str(id) if outF: print >>outF,'\n'.join(nmDict.values()) if molsOut and ids: molDbName = os.path.join(options.dbDir,options.molDbName) cns = [x.lower() for x in mConn.GetColumnNames('molecules')] if cns[-1]!='molpkl': cns.remove('molpkl') cns.append('molpkl') curs = mConn.GetCursor() #curs.execute('create temporary table _tmpTbl (guid integer)'%locals()) #curs.executemany('insert into _tmpTbl values (?)',ids) cnText=','.join(cns) curs.execute('select %(cnText)s from molecules join _tmpTbl using (%(idCol)s)'%locals()) row=curs.fetchone() molD = {} while row: row = list(row) pkl = row[-1] m = Chem.Mol(str(pkl)) guid = row[0] nm = nmDict[guid] if sdfOut: m.SetProp('_Name',nm) print >>sdfOut,Chem.MolToMolBlock(m) for i in range(1,len(cns)-1): pn = cns[i] pv = str(row[i]) print >>sdfOut,'> <%s>\n%s\n'%(pn,pv) print >>sdfOut,'$$$$' if smilesOut: smi=Chem.MolToSmiles(m,options.chiralSmiles) if smilesOut: print >>smilesOut,'%s %s'%(smi,str(row[1])) row=curs.fetchone() if not options.silent: logger.info('Done!') # ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- import os from optparse import OptionParser parser=OptionParser(_usage,version='%prog '+_version) parser.add_option('--dbDir',default='/db/camm/CURRENT/rdk_db', help='name of the directory containing the database information. The default is %default') parser.add_option('--molDbName',default='Compounds.sqlt', help='name of the molecule database') parser.add_option('--molIdName',default='compound_id', help='name of the database key column') parser.add_option('--regName',default='molecules', help='name of the molecular registry table') parser.add_option('--pairDbName',default='AtomPairs.sqlt', help='name of the atom pairs database') parser.add_option('--pairTableName',default='atompairs', help='name of the atom pairs table') parser.add_option('--pairColName',default='atompairfp', help='name of the atom pair column') parser.add_option('--torsionsDbName',default='AtomPairs.sqlt', help='name of the topological torsions database (usually the same as the atom pairs database)') parser.add_option('--torsionsTableName',default='atompairs', help='name of the topological torsions table (usually the same as the atom pairs table)') parser.add_option('--torsionsColName',default='torsionfp', help='name of the atom pair column') parser.add_option('--fpDbName',default='Fingerprints.sqlt', help='name of the 2D fingerprints database') parser.add_option('--fpTableName',default='rdkitfps', help='name of the 2D fingerprints table') parser.add_option('--layeredTableName',default='layeredfps', help='name of the layered fingerprints table') parser.add_option('--fpColName',default='', help='name of the 2D fingerprint column, a sensible default is used') parser.add_option('--descrDbName',default='Descriptors.sqlt', help='name of the descriptor database') parser.add_option('--descrTableName',default='descriptors_v1', help='name of the descriptor table') parser.add_option('--descriptorCalcFilename',default=os.path.join(RDConfig.RDBaseDir,'Projects', 'DbCLI','moe_like.dsc'), help='name of the file containing the descriptor calculator') parser.add_option('--outputDelim',default=',', help='the delimiter for the output file. The default is %default') parser.add_option('--topN',default=20,type='int', help='the number of neighbors to keep for each query compound. The default is %default') parser.add_option('--outF','--outFile',default='-', help='The name of the output file. The default is the console (stdout).') parser.add_option('--transpose',default=False,action="store_true", help='print the results out in a transposed form: e.g. neighbors in rows and probe compounds in columns') parser.add_option('--molFormat',default='sdf',choices=('smiles','sdf'), help='specify the format of the input file') parser.add_option('--nameProp',default='_Name', help='specify the SD property to be used for the molecule names. Default is to use the mol block name') parser.add_option('--smartsQuery','--smarts','--sma',default='', help='provide a SMARTS to be used as a substructure query') parser.add_option('--smilesQuery','--smiles','--smi',default='', help='provide a SMILES to be used as a substructure query') parser.add_option('--negateQuery','--negate',default=False,action='store_true', help='negate the results of the smarts query.') parser.add_option('--propQuery','--query','-q',default='', help='provide a property query (see the NOTE about property names)') parser.add_option('--sdfOut','--sdOut',default='', help='export an SD file with the matching molecules') parser.add_option('--smilesOut','--smiOut',default='', help='export a smiles file with the matching molecules') parser.add_option('--nonchiralSmiles',dest='chiralSmiles',default=True,action='store_false', help='do not use chiral SMILES in the output') parser.add_option('--silent',default=False,action='store_true', help='Do not generate status messages.') parser.add_option('--zipMols','--zip',default=False,action='store_true', help='read compressed mols from the database') parser.add_option('--pharm2DTableName',default='pharm2dfps', help='name of the Pharm2D fingerprints table') parser.add_option('--fdefFile','--fdef', default=os.path.join(RDConfig.RDDataDir,'Novartis1.fdef'), help='provide the name of the fdef file to use for 2d pharmacophores') parser.add_option('--gobbi2DTableName',default='gobbi2dfps', help='name of the Gobbi2D fingerprints table') parser.add_option('--similarityType','--simType','--sim', default='RDK',choices=supportedSimilarityMethods, help='Choose the type of similarity to use, possible values: RDK, AtomPairs, TopologicalTorsions, Pharm2D, Gobbi2D, Avalon, Morgan. The default is %default') parser.add_option('--morganFpDbName',default='Fingerprints.sqlt', help='name of the morgan fingerprints database') parser.add_option('--morganFpTableName',default='morganfps', help='name of the morgan fingerprints table') parser.add_option('--morganFpColName',default='morganfp', help='name of the morgan fingerprint column') if __name__=='__main__': import sys,getopt,time options,args = parser.parse_args() if len(args)!=1 and not (options.smilesQuery or options.smartsQuery or options.propQuery): parser.error('please either provide a query filename argument or do a data or smarts query') if len(args): queryFilename=args[0] else: queryFilename=None options.queryMol=None RunSearch(options,queryFilename)
{ "repo_name": "rdkit/rdkit-orig", "path": "Projects/DbCLI/SearchDb.py", "copies": "1", "size": "22342", "license": "bsd-3-clause", "hash": 7288779102083741000, "line_mean": 38.1278458844, "line_max": 175, "alpha_frac": 0.6547309999, "autogenerated": false, "ratio": 3.537925574030087, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4692656573930087, "avg_score": null, "num_lines": null }
_version = "0.13.0" _usage=""" CreateDb [optional arguments] <filename> NOTES: - the property names for the database are the union of those for all molecules. - missing property values will be set to 'N/A', though this can be changed with the --missingPropertyVal argument. - The property names may be altered on loading the database. Any non-alphanumeric character in a property name will be replaced with '_'. e.g. "Gold.Goldscore.Constraint.Score" becomes "Gold_Goldscore_Constraint_Score". This is important to know when querying. - Property names are not case sensitive in the database; this may cause some problems if they are case sensitive in the sd file. """ from rdkit import RDConfig from rdkit import Chem from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbModule from rdkit.RDLogger import logger from rdkit.Chem.MolDb import Loader logger = logger() import cPickle,sys,os from rdkit.Chem.MolDb.FingerprintUtils import BuildSigFactory,LayeredOptions from rdkit.Chem.MolDb import FingerprintUtils # ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- from optparse import OptionParser parser=OptionParser(_usage,version='%prog '+_version) parser.add_option('--outDir','--dbDir',default='', help='name of the output directory') parser.add_option('--molDbName',default='Compounds.sqlt', help='name of the molecule database') parser.add_option('--molIdName',default='compound_id', help='name of the database key column') parser.add_option('--regName',default='molecules', help='name of the molecular registry table') parser.add_option('--pairDbName',default='AtomPairs.sqlt', help='name of the atom pairs database') parser.add_option('--pairTableName',default='atompairs', help='name of the atom pairs table') parser.add_option('--fpDbName',default='Fingerprints.sqlt', help='name of the 2D fingerprints database') parser.add_option('--fpTableName',default='rdkitfps', help='name of the 2D fingerprints table') parser.add_option('--layeredTableName',default='layeredfps', help='name of the layered fingerprints table') parser.add_option('--descrDbName',default='Descriptors.sqlt', help='name of the descriptor database') parser.add_option('--descrTableName',default='descriptors_v1', help='name of the descriptor table') parser.add_option('--descriptorCalcFilename',default=os.path.join(RDConfig.RDBaseDir,'Projects', 'DbCLI','moe_like.dsc'), help='name of the file containing the descriptor calculator') parser.add_option('--errFilename',default='loadErrors.txt', help='name of the file to contain information about molecules that fail to load') parser.add_option('--noPairs',default=True,dest='doPairs',action='store_false', help='skip calculating atom pairs') parser.add_option('--noFingerprints',default=True,dest='doFingerprints',action='store_false', help='skip calculating 2D fingerprints') parser.add_option('--noLayeredFps',default=True,dest='doLayered',action='store_false', help='skip calculating layered fingerprints') parser.add_option('--noDescriptors',default=True,dest='doDescriptors',action='store_false', help='skip calculating descriptors') parser.add_option('--noProps',default=False,dest='skipProps',action='store_true', help="don't include molecular properties in the database") parser.add_option('--noSmiles',default=False,dest='skipSmiles',action='store_true', help="don't include SMILES in the database (can make loading somewhat faster)") parser.add_option('--maxRowsCached',default=-1, help="maximum number of rows to cache before doing a database commit") parser.add_option('--silent',default=False,action='store_true', help='do not provide status messages') parser.add_option('--molFormat',default='',choices=('smiles','sdf',''), help='specify the format of the input file') parser.add_option('--nameProp',default='_Name', help='specify the SD property to be used for the molecule names. Default is to use the mol block name') parser.add_option('--missingPropertyVal',default='N/A', help='value to insert in the database if a property value is missing. Default is %default.') parser.add_option('--addProps',default=False,action='store_true', help='add computed properties to the output') parser.add_option('--noExtras',default=False,action='store_true', help='skip all non-molecule databases') parser.add_option('--skipLoad','--skipMols',action="store_false",dest='loadMols',default=True, help='skip the molecule loading (assumes mol db already exists)') parser.add_option('--doPharm2D',default=False, action='store_true', help='skip calculating Pharm2D fingerprints') parser.add_option('--pharm2DTableName',default='pharm2dfps', help='name of the Pharm2D fingerprints table') parser.add_option('--fdefFile','--fdef', default=os.path.join(RDConfig.RDDataDir,'Novartis1.fdef'), help='provide the name of the fdef file to use for 2d pharmacophores') parser.add_option('--doGobbi2D',default=False, action='store_true', help='skip calculating Gobbi 2D fingerprints') parser.add_option('--gobbi2DTableName',default='gobbi2dfps', help='name of the Gobbi 2D fingerprints table') parser.add_option('--noMorganFps','--noCircularFps',default=True,dest='doMorganFps',action='store_false', help='skip calculating Morgan (circular) fingerprints') parser.add_option('--morganFpTableName',default='morganfps', help='name of the Morgan fingerprints table') parser.add_option('--delimiter','--delim',default=' ', help='the delimiter in the input file') parser.add_option('--titleLine',default=False,action='store_true', help='the input file contains a title line') parser.add_option('--smilesColumn','--smilesCol',default=0,type='int', help='the column index with smiles') parser.add_option('--nameColumn','--nameCol',default=1,type='int', help='the column index with mol names') def CreateDb(options,dataFilename='',supplier=None): if not dataFilename and supplier is None: raise ValueError,'Please provide either a data filename or a supplier' if options.errFilename: errFile=file(os.path.join(options.outDir,options.errFilename),'w+') else: errFile=None if options.noExtras: options.doPairs=False options.doDescriptors=False options.doFingerprints=False options.doPharm2D=False options.doGobbi2D=False options.doLayered=False options.doMorganFps=False if options.loadMols: if supplier is None: if not options.molFormat: ext = os.path.splitext(dataFilename)[-1].lower() if ext=='.sdf': options.molFormat='sdf' elif ext in ('.smi','.smiles','.txt','.csv'): options.molFormat='smiles' if not options.delimiter: # guess the delimiter import csv sniffer = csv.Sniffer() dlct=sniffer.sniff(file(dataFilename,'r').read(2000)) options.delimiter=dlct.delimiter if not options.silent: logger.info('Guessing that delimiter is %s. Use --delimiter argument if this is wrong.'%repr(options.delimiter)) if not options.silent: logger.info('Guessing that mol format is %s. Use --molFormat argument if this is wrong.'%repr(options.molFormat)) if options.molFormat=='smiles': if options.delimiter=='\\t': options.delimiter='\t' supplier=Chem.SmilesMolSupplier(dataFilename, titleLine=options.titleLine, delimiter=options.delimiter, smilesColumn=options.smilesColumn, nameColumn=options.nameColumn ) else: supplier = Chem.SDMolSupplier(dataFilename) if not options.silent: logger.info('Reading molecules and constructing molecular database.') Loader.LoadDb(supplier,os.path.join(options.outDir,options.molDbName), errorsTo=errFile,regName=options.regName,nameCol=options.molIdName, skipProps=options.skipProps,defaultVal=options.missingPropertyVal, addComputedProps=options.addProps,uniqNames=True, skipSmiles=options.skipSmiles,maxRowsCached=int(options.maxRowsCached), silent=options.silent,nameProp=options.nameProp, lazySupplier=int(options.maxRowsCached)>0) if options.doPairs: pairConn = DbConnect(os.path.join(options.outDir,options.pairDbName)) pairCurs = pairConn.GetCursor() try: pairCurs.execute('drop table %s'%(options.pairTableName)) except: pass pairCurs.execute('create table %s (guid integer not null primary key,%s varchar not null unique,atompairfp blob,torsionfp blob)'%(options.pairTableName, options.molIdName)) if options.doFingerprints or options.doPharm2D or options.doGobbi2D or options.doLayered: fpConn = DbConnect(os.path.join(options.outDir,options.fpDbName)) fpCurs=fpConn.GetCursor() try: fpCurs.execute('drop table %s'%(options.fpTableName)) except: pass try: fpCurs.execute('drop table %s'%(options.pharm2DTableName)) except: pass try: fpCurs.execute('drop table %s'%(options.gobbi2DTableName)) except: pass try: fpCurs.execute('drop table %s'%(options.layeredTableName)) except: pass if options.doFingerprints: fpCurs.execute('create table %s (guid integer not null primary key,%s varchar not null unique,rdkfp blob)'%(options.fpTableName, options.molIdName)) if options.doLayered: layeredQs = ','.join('?'*LayeredOptions.nWords) colDefs=','.join(['Col_%d integer'%(x+1) for x in range(LayeredOptions.nWords)]) fpCurs.execute('create table %s (guid integer not null primary key,%s varchar not null unique,%s)'%(options.layeredTableName, options.molIdName, colDefs)) if options.doPharm2D: fpCurs.execute('create table %s (guid integer not null primary key,%s varchar not null unique,pharm2dfp blob)'%(options.pharm2DTableName, options.molIdName)) sigFactory = BuildSigFactory(options) if options.doGobbi2D: fpCurs.execute('create table %s (guid integer not null primary key,%s varchar not null unique,gobbi2dfp blob)'%(options.gobbi2DTableName, options.molIdName)) from rdkit.Chem.Pharm2D import Generate,Gobbi_Pharm2D if options.doMorganFps : fpConn = DbConnect(os.path.join(options.outDir,options.fpDbName)) fpCurs=fpConn.GetCursor() try: fpCurs.execute('drop table %s'%(options.morganFpTableName)) except: pass fpCurs.execute('create table %s (guid integer not null primary key,%s varchar not null unique,morganfp blob)'%(options.morganFpTableName, options.molIdName)) if options.doDescriptors: descrConn=DbConnect(os.path.join(options.outDir,options.descrDbName)) calc = cPickle.load(file(options.descriptorCalcFilename,'rb')) nms = [x for x in calc.GetDescriptorNames()] descrCurs = descrConn.GetCursor() descrs = ['guid integer not null primary key','%s varchar not null unique'%options.molIdName] descrs.extend(['%s float'%x for x in nms]) try: descrCurs.execute('drop table %s'%(options.descrTableName)) except: pass descrCurs.execute('create table %s (%s)'%(options.descrTableName,','.join(descrs))) descrQuery=','.join([DbModule.placeHolder]*len(descrs)) pairRows = [] fpRows = [] layeredRows = [] descrRows = [] pharm2DRows=[] gobbi2DRows=[] morganRows = [] if not options.silent: logger.info('Generating fingerprints and descriptors:') molConn = DbConnect(os.path.join(options.outDir,options.molDbName)) molCurs = molConn.GetCursor() if not options.skipSmiles: molCurs.execute('select guid,%s,smiles,molpkl from %s'%(options.molIdName,options.regName)) else: molCurs.execute('select guid,%s,molpkl from %s'%(options.molIdName,options.regName)) i=0 while 1: try: tpl = molCurs.fetchone() molGuid = tpl[0] molId = tpl[1] pkl = tpl[-1] i+=1 except: break mol = Chem.Mol(str(pkl)) if not mol: continue if options.doPairs: pairs = FingerprintUtils.BuildAtomPairFP(mol) torsions = FingerprintUtils.BuildTorsionsFP(mol) pkl1 = DbModule.binaryHolder(pairs.ToBinary()) pkl2 = DbModule.binaryHolder(torsions.ToBinary()) row = (molGuid,molId,pkl1,pkl2) pairRows.append(row) if options.doFingerprints: fp2 = FingerprintUtils.BuildRDKitFP(mol) pkl = DbModule.binaryHolder(fp2.ToBinary()) row = (molGuid,molId,pkl) fpRows.append(row) if options.doLayered: words = LayeredOptions.GetWords(mol) row = [molGuid,molId]+words layeredRows.append(row) if options.doDescriptors: descrs= calc.CalcDescriptors(mol) row = [molGuid,molId] row.extend(descrs) descrRows.append(row) if options.doPharm2D: FingerprintUtils.sigFactory=sigFactory fp= FingerprintUtils.BuildPharm2DFP(mol) pkl = DbModule.binaryHolder(fp.ToBinary()) row = (molGuid,molId,pkl) pharm2DRows.append(row) if options.doGobbi2D: FingerprintUtils.sigFactory=Gobbi_Pharm2D.factory fp= FingerprintUtils.BuildPharm2DFP(mol) pkl = DbModule.binaryHolder(fp.ToBinary()) row = (molGuid,molId,pkl) gobbi2DRows.append(row) if options.doMorganFps: morgan = FingerprintUtils.BuildMorganFP(mol) pkl = DbModule.binaryHolder(morgan.ToBinary()) row = (molGuid,molId,pkl) morganRows.append(row) if not i%500: if len(pairRows): pairCurs.executemany('insert into %s values (?,?,?,?)'%options.pairTableName, pairRows) pairRows = [] pairConn.Commit() if len(fpRows): fpCurs.executemany('insert into %s values (?,?,?)'%options.fpTableName, fpRows) fpRows = [] fpConn.Commit() if len(layeredRows): fpCurs.executemany('insert into %s values (?,?,%s)'%(options.layeredTableName,layeredQs), layeredRows) layeredRows = [] fpConn.Commit() if len(descrRows): descrCurs.executemany('insert into %s values (%s)'%(options.descrTableName,descrQuery), descrRows) descrRows = [] descrConn.Commit() if len(pharm2DRows): fpCurs.executemany('insert into %s values (?,?,?)'%options.pharm2DTableName, pharm2DRows) pharm2DRows = [] fpConn.Commit() if len(gobbi2DRows): fpCurs.executemany('insert into %s values (?,?,?)'%options.gobbi2DTableName, gobbi2DRows) gobbi2DRows = [] fpConn.Commit() if len(morganRows): fpCurs.executemany('insert into %s values (?,?,?)'%options.morganFpTableName, morganRows) morganRows = [] fpConn.Commit() if not options.silent and not i%500: logger.info(' Done: %d'%(i)) if len(pairRows): pairCurs.executemany('insert into %s values (?,?,?,?)'%options.pairTableName, pairRows) pairRows = [] pairConn.Commit() if len(fpRows): fpCurs.executemany('insert into %s values (?,?,?)'%options.fpTableName, fpRows) fpRows = [] fpConn.Commit() if len(layeredRows): fpCurs.executemany('insert into %s values (?,?,%s)'%(options.layeredTableName,layeredQs), layeredRows) layeredRows = [] fpConn.Commit() if len(descrRows): descrCurs.executemany('insert into %s values (%s)'%(options.descrTableName,descrQuery), descrRows) descrRows = [] descrConn.Commit() if len(pharm2DRows): fpCurs.executemany('insert into %s values (?,?,?)'%options.pharm2DTableName, pharm2DRows) pharm2DRows = [] fpConn.Commit() if len(gobbi2DRows): fpCurs.executemany('insert into %s values (?,?,?)'%options.gobbi2DTableName, gobbi2DRows) gobbi2DRows = [] fpConn.Commit() if len(morganRows): fpCurs.executemany('insert into %s values (?,?,?)'%options.morganFpTableName, morganRows) morganRows = [] fpConn.Commit() if not options.silent: logger.info('Finished.') if __name__=='__main__': options,args = parser.parse_args() if options.loadMols: if len(args)!=1: parser.error('please provide a filename argument') dataFilename = args[0] try: dataFile = file(dataFilename,'r') except IOError: logger.error('input file %s does not exist'%(dataFilename)) sys.exit(0) dataFile=None if not options.outDir: prefix = os.path.splitext(dataFilename)[0] options.outDir=prefix if not os.path.exists(options.outDir): try: os.mkdir(options.outDir) except: logger.error('could not create output directory %s'%options.outDir) sys.exit(1) if 1: CreateDb(options,dataFilename) else: import cProfile cProfile.run("CreateDb(options,dataFilename)","create.prof") import pstats p = pstats.Stats('create.prof') p.strip_dirs().sort_stats('cumulative').print_stats(25)
{ "repo_name": "rdkit/rdkit-orig", "path": "Projects/DbCLI/CreateDb.py", "copies": "1", "size": "20427", "license": "bsd-3-clause", "hash": 7043198854838798000, "line_mean": 43.2142857143, "line_max": 156, "alpha_frac": 0.636461546, "autogenerated": false, "ratio": 3.8497926875235584, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4986254233523558, "avg_score": null, "num_lines": null }
from rdkit import rdBase from rdkit import Chem from rdkit.Chem import rdChemReactions from rdkit import Geometry from rdkit import RDConfig import unittest import os,sys import cPickle def feq(v1,v2,tol2=1e-4): return abs(v1-v2)<=tol2 def ptEq(pt1, pt2, tol=1e-4): return feq(pt1.x,pt2.x,tol) and feq(pt1.y,pt2.y,tol) and feq(pt1.z,pt2.z,tol) class TestCase(unittest.TestCase) : def setUp(self): self.dataDir = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','ChemReactions','testData') def test1Basics(self): rxn = rdChemReactions.ChemicalReaction() self.failUnless(rxn.GetNumReactantTemplates()==0) self.failUnless(rxn.GetNumProductTemplates()==0) r1= Chem.MolFromSmarts('[C:1](=[O:2])O') rxn.AddReactantTemplate(r1) self.failUnless(rxn.GetNumReactantTemplates()==1) r1= Chem.MolFromSmarts('[N:3]') rxn.AddReactantTemplate(r1) self.failUnless(rxn.GetNumReactantTemplates()==2) r1= Chem.MolFromSmarts('[C:1](=[O:2])[N:3]') rxn.AddProductTemplate(r1) self.failUnless(rxn.GetNumProductTemplates()==1) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) self.failUnless(len(ps)==1) self.failUnless(len(ps[0])==1) self.failUnless(ps[0][0].GetNumAtoms()==3) ps = rxn.RunReactants(list(reacts)) self.failUnless(len(ps)==1) self.failUnless(len(ps[0])==1) self.failUnless(ps[0][0].GetNumAtoms()==3) def test2DaylightParser(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]') self.failUnless(rxn) self.failUnless(rxn.GetNumReactantTemplates()==2) self.failUnless(rxn.GetNumProductTemplates()==1) self.failUnless(rxn._getImplicitPropertiesFlag()) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) self.failUnless(len(ps)==1) self.failUnless(len(ps[0])==1) self.failUnless(ps[0][0].GetNumAtoms()==3) reacts = (Chem.MolFromSmiles('CC(=O)OC'),Chem.MolFromSmiles('CN')) ps = rxn.RunReactants(reacts) self.failUnless(len(ps)==1) self.failUnless(len(ps[0])==1) self.failUnless(ps[0][0].GetNumAtoms()==5) def test3MDLParsers(self): fileN = os.path.join(self.dataDir,'AmideBond.rxn') rxn = rdChemReactions.ReactionFromRxnFile(fileN) self.failUnless(rxn) self.failIf(rxn._getImplicitPropertiesFlag()) self.failUnless(rxn.GetNumReactantTemplates()==2) self.failUnless(rxn.GetNumProductTemplates()==1) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) self.failUnless(len(ps)==1) self.failUnless(len(ps[0])==1) self.failUnless(ps[0][0].GetNumAtoms()==3) rxnBlock = file(fileN,'r').read() rxn = rdChemReactions.ReactionFromRxnBlock(rxnBlock) self.failUnless(rxn) self.failUnless(rxn.GetNumReactantTemplates()==2) self.failUnless(rxn.GetNumProductTemplates()==1) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) self.failUnless(len(ps)==1) self.failUnless(len(ps[0])==1) self.failUnless(ps[0][0].GetNumAtoms()==3) def test4ErrorHandling(self): self.failUnlessRaises(ValueError,lambda x='[C:1](=[O:2])Q.[N:3]>>[C:1](=[O:2])[N:3]':rdChemReactions.ReactionFromSmarts(x)) self.failUnlessRaises(ValueError,lambda x='[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]Q':rdChemReactions.ReactionFromSmarts(x)) self.failUnlessRaises(ValueError,lambda x='[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]>>CC':rdChemReactions.ReactionFromSmarts(x)) block="""$RXN ISIS 082120061354 3 1 $MOL -ISIS- 08210613542D 3 2 0 0 0 0 0 0 0 0999 V2000 -1.4340 -0.6042 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 -0.8639 -0.9333 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 -1.4340 0.0542 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 1 3 2 0 0 0 0 M END $MOL -ISIS- 08210613542D 1 0 0 0 0 0 0 0 0 0999 V2000 2.2125 -0.7833 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 M END $MOL -ISIS- 08210613542D 3 2 0 0 0 0 0 0 0 0999 V2000 9.5282 -0.8083 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 8.9579 -0.4792 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 8.9579 0.1792 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 2 3 2 0 0 0 0 M END """ self.failUnlessRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) block="""$RXN ISIS 082120061354 2 1 $MOL -ISIS- 08210613542D 4 2 0 0 0 0 0 0 0 0999 V2000 -1.4340 -0.6042 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 -0.8639 -0.9333 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 -1.4340 0.0542 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 1 3 2 0 0 0 0 M END $MOL -ISIS- 08210613542D 1 0 0 0 0 0 0 0 0 0999 V2000 2.2125 -0.7833 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 M END $MOL -ISIS- 08210613542D 3 2 0 0 0 0 0 0 0 0999 V2000 9.5282 -0.8083 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 8.9579 -0.4792 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 8.9579 0.1792 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 2 3 2 0 0 0 0 M END """ #self.failUnlessRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) block="""$RXN ISIS 082120061354 2 1 $MOL -ISIS- 08210613542D 3 2 0 0 0 0 0 0 0 0999 V2000 -1.4340 -0.6042 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 -0.8639 -0.9333 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 -1.4340 0.0542 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 1 3 2 0 0 0 0 M END $MOL -ISIS- 08210613542D 1 0 0 0 0 0 0 0 0 0999 V2000 2.2125 -0.7833 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 M END $MOL -ISIS- 08210613542D 3 1 0 0 0 0 0 0 0 0999 V2000 9.5282 -0.8083 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0 8.9579 -0.4792 0.0000 C 0 0 0 0 0 0 0 0 0 2 0 0 8.9579 0.1792 0.0000 O 0 0 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 0 0 2 3 2 0 0 0 0 M END """ #self.failUnlessRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) def test5Validation(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]') self.failUnless(rxn) self.failUnless(rxn.Validate()==(0,0)) rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:1])O.[N:3]>>[C:1](=[O:2])[N:3]') self.failUnless(rxn) self.failUnless(rxn.Validate()==(1,1)) rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])[O:4].[N:3]>>[C:1](=[O:2])[N:3]') self.failUnless(rxn) self.failUnless(rxn.Validate()==(1,0)) rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3][C:5]') self.failUnless(rxn) self.failUnless(rxn.Validate()==(1,0)) def test6Exceptions(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]Cl>>[C:1]') self.failUnless(rxn) self.failUnlessRaises(ValueError,lambda x=rxn:x.RunReactants(())) self.failUnlessRaises(ValueError,lambda x=rxn:x.RunReactants((Chem.MolFromSmiles('CC'),Chem.MolFromSmiles('C')))) ps=rxn.RunReactants((Chem.MolFromSmiles('CCCl'),)) self.failUnless(len(ps)==1) self.failUnless(len(ps[0])==1) def _test7Leak(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]Cl>>[C:1]') self.failUnless(rxn) print 'running: ' for i in range(1e5): ps=rxn.RunReactants((Chem.MolFromSmiles('CCCl'),)) self.failUnless(len(ps)==1) self.failUnless(len(ps[0])==1) if not i%1000: print i def test8Properties(self): rxn = rdChemReactions.ReactionFromSmarts('[O:1]>>[O:1][3#0]') self.failUnless(rxn) ps=rxn.RunReactants((Chem.MolFromSmiles('CO'),)) self.failUnless(len(ps)==1) self.failUnless(len(ps[0])==1) Chem.SanitizeMol(ps[0][0]) self.failUnlessEqual(ps[0][0].GetAtomWithIdx(1).GetIsotope(),3); def test9AromaticityTransfer(self): # this was issue 2664121 mol = Chem.MolFromSmiles('c1ccc(C2C3(Cc4c(cccc4)C2)CCCC3)cc1') rxn = rdChemReactions.ReactionFromSmarts('[A:1]1~[*:2]~[*:3]~[*:4]~[*:5]~[A:6]-;@1>>[*:1]~[*:2]~[*:3]~[*:4]~[*:5]~[*:6]') products = rxn.RunReactants([mol]) self.failUnlessEqual(len(products),6) for p in products: self.failUnlessEqual(len(p),1) Chem.SanitizeMol(p[0]) def test10DotSeparation(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]1[O:2][N:3]1>>[C:1]1[O:2].[N:3]1') mol = Chem.MolFromSmiles('C1ON1') products = rxn.RunReactants([mol]) self.failUnlessEqual(len(products),1) for p in products: self.failUnlessEqual(len(p),1) self.failUnlessEqual(p[0].GetNumAtoms(),3) self.failUnlessEqual(p[0].GetNumBonds(),2) def test11ImplicitProperties(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]O>>[C:1]') mol = Chem.MolFromSmiles('CCO') products = rxn.RunReactants([mol]) self.failUnlessEqual(len(products),1) for p in products: self.failUnlessEqual(len(p),1) self.failUnlessEqual(Chem.MolToSmiles(p[0]),'CC') mol2 = Chem.MolFromSmiles('C[CH-]O') products = rxn.RunReactants([mol2]) self.failUnlessEqual(len(products),1) for p in products: self.failUnlessEqual(len(p),1) self.failUnlessEqual(Chem.MolToSmiles(p[0]),'[CH2-]C') rxn._setImplicitPropertiesFlag(False) products = rxn.RunReactants([mol]) self.failUnlessEqual(len(products),1) for p in products: self.failUnlessEqual(len(p),1) self.failUnlessEqual(Chem.MolToSmiles(p[0]),'CC') products = rxn.RunReactants([mol2]) self.failUnlessEqual(len(products),1) for p in products: self.failUnlessEqual(len(p),1) self.failUnlessEqual(Chem.MolToSmiles(p[0]),'CC') def test12Pickles(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]1[O:2][N:3]1>>[C:1]1[O:2].[N:3]1') pkl = cPickle.dumps(rxn) rxn = cPickle.loads(pkl) mol = Chem.MolFromSmiles('C1ON1') products = rxn.RunReactants([mol]) self.failUnlessEqual(len(products),1) for p in products: self.failUnlessEqual(len(p),1) self.failUnlessEqual(p[0].GetNumAtoms(),3) self.failUnlessEqual(p[0].GetNumBonds(),2) rxn = rdChemReactions.ChemicalReaction(rxn.ToBinary()) products = rxn.RunReactants([mol]) self.failUnlessEqual(len(products),1) for p in products: self.failUnlessEqual(len(p),1) self.failUnlessEqual(p[0].GetNumAtoms(),3) self.failUnlessEqual(p[0].GetNumBonds(),2) def test13GetTemplates(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]1[O:2][N:3]1>>[C:1][O:2].[N:3]') r1 = rxn.GetReactantTemplate(0) sma=Chem.MolToSmarts(r1) self.failUnlessEqual(sma,'[C:1]1-,:[O:2]-,:[N:3]-,:1') p1 = rxn.GetProductTemplate(0) sma=Chem.MolToSmarts(p1) self.failUnlessEqual(sma,'[C:1]-,:[O:2]') p2 = rxn.GetProductTemplate(1) sma=Chem.MolToSmarts(p2) self.failUnlessEqual(sma,'[N:3]') self.failUnlessRaises(ValueError,lambda :rxn.GetProductTemplate(2)) self.failUnlessRaises(ValueError,lambda :rxn.GetReactantTemplate(1)) def test14Matchers(self): rxn = rdChemReactions.ReactionFromSmarts('[C;!$(C(-O)-O):1](=[O:2])[O;H,-1].[N;!H0:3]>>[C:1](=[O:2])[N:3]') self.failUnless(rxn) rxn.Initialize() self.failUnless(rxn.IsMoleculeReactant(Chem.MolFromSmiles('OC(=O)C'))) self.failIf(rxn.IsMoleculeReactant(Chem.MolFromSmiles('OC(=O)O'))) self.failUnless(rxn.IsMoleculeReactant(Chem.MolFromSmiles('CNC'))) self.failIf(rxn.IsMoleculeReactant(Chem.MolFromSmiles('CN(C)C'))) self.failUnless(rxn.IsMoleculeProduct(Chem.MolFromSmiles('NC(=O)C'))) self.failUnless(rxn.IsMoleculeProduct(Chem.MolFromSmiles('CNC(=O)C'))) self.failIf(rxn.IsMoleculeProduct(Chem.MolFromSmiles('COC(=O)C'))) def test15Replacements(self): rxn = rdChemReactions.ReactionFromSmarts('[{amine}:1]>>[*:1]-C', replacements={'{amine}':'$([N;!H0;$(N-[#6]);!$(N-[!#6;!#1]);!$(N-C=[O,N,S])])'}) self.failUnless(rxn) rxn.Initialize() reactants = (Chem.MolFromSmiles('CCN'),) ps = rxn.RunReactants(reactants) self.failUnlessEqual(len(ps),1) self.failUnlessEqual(len(ps[0]),1) self.failUnlessEqual(ps[0][0].GetNumAtoms(),4) def test16GetReactingAtoms(self): rxn = rdChemReactions.ReactionFromSmarts("[O:1][C:2].[N:3]>>[N:1][C:2].[N:3]") self.failUnless(rxn) rxn.Initialize() rAs = rxn.GetReactingAtoms() self.failUnlessEqual(len(rAs),2) self.failUnlessEqual(len(rAs[0]),1) self.failUnlessEqual(len(rAs[1]),0) rxn = rdChemReactions.ReactionFromSmarts("[O:1]C>>[O:1]C") self.failUnless(rxn) rxn.Initialize() rAs = rxn.GetReactingAtoms() self.failUnlessEqual(len(rAs),1) self.failUnlessEqual(len(rAs[0]),2) rAs = rxn.GetReactingAtoms(True) self.failUnlessEqual(len(rAs),1) self.failUnlessEqual(len(rAs[0]),1) def test17AddRecursiveQueriesToReaction(self): rxn = rdChemReactions.ReactionFromSmarts("[C:1][O:2].[N:3]>>[C:1][N:2]") self.failUnless(rxn) rxn.Initialize() qs = {'aliphatic':Chem.MolFromSmiles('CC')} rxn.GetReactantTemplate(0).GetAtomWithIdx(0).SetProp('query', 'aliphatic') rxn.AddRecursiveQueriesToReaction(qs,'query') q = rxn.GetReactantTemplate(0) m = Chem.MolFromSmiles('CCOC') self.failUnless(m.HasSubstructMatch(q)) m = Chem.MolFromSmiles('CO') self.failIf(m.HasSubstructMatch(q)) rxn = rdChemReactions.ReactionFromSmarts("[C:1][O:2].[N:3]>>[C:1][N:2]") rxn.Initialize() rxn.GetReactantTemplate(0).GetAtomWithIdx(0).SetProp('query', 'aliphatic') labels = rxn.AddRecursiveQueriesToReaction(qs,'query', getLabels=True) self.failUnless(len(labels), 1) def test18GithubIssue16(self): rxn = rdChemReactions.ReactionFromSmarts("[F:1]>>[Cl:1]") self.failUnless(rxn) rxn.Initialize() self.failUnlessRaises(ValueError,lambda : rxn.RunReactants((None,))) if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "Code/GraphMol/ChemReactions/Wrap/testReactionWrapper.py", "copies": "2", "size": "16101", "license": "bsd-3-clause", "hash": -9066195625495830000, "line_mean": 35.5931818182, "line_max": 131, "alpha_frac": 0.6372896093, "autogenerated": false, "ratio": 2.5765722515602496, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42138618608602496, "avg_score": null, "num_lines": null }
""" Implementation of the RECAP algorithm from Lewell et al. JCICS *38* 511-522 (1998) The published algorithm is implemented more or less without modification. The results are returned as a hierarchy of nodes instead of just as a set of fragments. The hope is that this will allow a bit more flexibility in working with the results. For example: >>> m = Chem.MolFromSmiles('C1CC1Oc1ccccc1-c1ncc(OC)cc1') >>> res = Recap.RecapDecompose(m) >>> res <Chem.Recap.RecapHierarchyNode object at 0x00CDB5D0> >>> res.children.keys() ['[*]C1CC1', '[*]c1ccccc1-c1ncc(OC)cc1', '[*]c1ccc(OC)cn1', '[*]c1ccccc1OC1CC1'] >>> res.GetAllChildren().keys() ['[*]c1ccccc1[*]', '[*]C1CC1', '[*]c1ccccc1-c1ncc(OC)cc1', '[*]c1ccc(OC)cn1', '[*]c1ccccc1OC1CC1'] To get the standard set of RECAP results, use GetLeaves(): >>> leaves=res.GetLeaves() >>> leaves.keys() ['[*]c1ccccc1[*]', '[*]c1ccc(OC)cn1', '[*]C1CC1'] >>> leaf = leaves['[*]C1CC1'] >>> leaf.mol <Chem.rdchem.Mol object at 0x00CBE0F0> """ import sys import weakref from rdkit import Chem from rdkit.Chem import rdChemReactions as Reactions from rdkit.six import iterkeys, iteritems, next # These are the definitions that will be applied to fragment molecules: reactionDefs = ( "[#7;+0;D2,D3:1]!@C(!@=O)!@[#7;+0;D2,D3:2]>>[*][#7:1].[#7:2][*]", # urea "[C;!$(C([#7])[#7]):1](=!@[O:2])!@[#7;+0;!D1:3]>>[*][C:1]=[O:2].[*][#7:3]", # amide "[C:1](=!@[O:2])!@[O;+0:3]>>[*][C:1]=[O:2].[O:3][*]", # ester "[N;!D1;+0;!$(N-C=[#7,#8,#15,#16])](-!@[*:1])-!@[*:2]>>[*][*:1].[*:2][*]", # amines #"[N;!D1](!@[*:1])!@[*:2]>>[*][*:1].[*:2][*]", # amines # again: what about aromatics? "[#7;R;D3;+0:1]-!@[*:2]>>[*][#7:1].[*:2][*]", # cyclic amines "[#6:1]-!@[O;+0]-!@[#6:2]>>[#6:1][*].[*][#6:2]", # ether "[C:1]=!@[C:2]>>[C:1][*].[*][C:2]", # olefin "[n;+0:1]-!@[C:2]>>[n:1][*].[C:2][*]", # aromatic nitrogen - aliphatic carbon "[O:3]=[C:4]-@[N;+0:1]-!@[C:2]>>[O:3]=[C:4]-[N:1][*].[C:2][*]", # lactam nitrogen - aliphatic carbon "[c:1]-!@[c:2]>>[c:1][*].[*][c:2]", # aromatic carbon - aromatic carbon "[n;+0:1]-!@[c:2]>>[n:1][*].[*][c:2]", # aromatic nitrogen - aromatic carbon *NOTE* this is not part of the standard recap set. "[#7;+0;D2,D3:1]-!@[S:2](=[O:3])=[O:4]>>[#7:1][*].[*][S:2](=[O:3])=[O:4]", # sulphonamide ) reactions = tuple([Reactions.ReactionFromSmarts(x) for x in reactionDefs]) class RecapHierarchyNode(object): """ This class is used to hold the Recap hiearchy """ mol = None children = None parents = None smiles = None def __init__(self, mol): self.mol = mol self.children = {} self.parents = {} def GetAllChildren(self): " returns a dictionary, keyed by SMILES, of children " res = {} for smi, child in iteritems(self.children): res[smi] = child child._gacRecurse(res, terminalOnly=False) return res def GetLeaves(self): " returns a dictionary, keyed by SMILES, of leaf (terminal) nodes " res = {} for smi, child in iteritems(self.children): if not len(child.children): res[smi] = child else: child._gacRecurse(res, terminalOnly=True) return res def getUltimateParents(self): """ returns all the nodes in the hierarchy tree that contain this node as a child """ if not self.parents: res = [self] else: res = [] for p in self.parents.values(): for uP in p.getUltimateParents(): if uP not in res: res.append(uP) return res def _gacRecurse(self, res, terminalOnly=False): for smi, child in iteritems(self.children): if not terminalOnly or not len(child.children): res[smi] = child child._gacRecurse(res, terminalOnly=terminalOnly) def __del__(self): self.children = {} self.parent = {} self.mol = None def RecapDecompose(mol, allNodes=None, minFragmentSize=0, onlyUseReactions=None): """ returns the recap decomposition for a molecule """ mSmi = Chem.MolToSmiles(mol, 1) if allNodes is None: allNodes = {} if mSmi in allNodes: return allNodes[mSmi] res = RecapHierarchyNode(mol) res.smiles = mSmi activePool = {mSmi: res} allNodes[mSmi] = res while activePool: nSmi = next(iterkeys(activePool)) node = activePool.pop(nSmi) if not node.mol: continue for rxnIdx, reaction in enumerate(reactions): if onlyUseReactions and rxnIdx not in onlyUseReactions: continue #print ' .',nSmi #print ' !!!!',rxnIdx,nSmi,reactionDefs[rxnIdx] ps = reaction.RunReactants((node.mol, )) #print ' ',len(ps) if ps: for prodSeq in ps: seqOk = True # we want to disqualify small fragments, so sort the product sequence by size # and then look for "forbidden" fragments tSeq = [(prod.GetNumAtoms(onlyExplicit=True), idx) for idx, prod in enumerate(prodSeq)] tSeq.sort() ts = [(x, prodSeq[y]) for x, y in tSeq] prodSeq = ts for nats, prod in prodSeq: try: Chem.SanitizeMol(prod) except Exception: continue pSmi = Chem.MolToSmiles(prod, 1) if minFragmentSize > 0: nDummies = pSmi.count('*') if nats - nDummies < minFragmentSize: seqOk = False break # don't forget after replacing dummy atoms to remove any empty # branches: elif pSmi.replace('[*]', '').replace('()', '') in ('', 'C', 'CC', 'CCC'): seqOk = False break prod.pSmi = pSmi if seqOk: for nats, prod in prodSeq: pSmi = prod.pSmi #print '\t',nats,pSmi if not pSmi in allNodes: pNode = RecapHierarchyNode(prod) pNode.smiles = pSmi pNode.parents[nSmi] = weakref.proxy(node) node.children[pSmi] = pNode activePool[pSmi] = pNode allNodes[pSmi] = pNode else: pNode = allNodes[pSmi] pNode.parents[nSmi] = weakref.proxy(node) node.children[pSmi] = pNode #print ' >>an:',allNodes.keys() return res # ------- ------- ------- ------- ------- ------- ------- ------- # Begin testing code if __name__ == '__main__': import unittest class TestCase(unittest.TestCase): def test1(self): m = Chem.MolFromSmiles('C1CC1Oc1ccccc1-c1ncc(OC)cc1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.children.keys()) == 4) self.assertTrue(len(res.GetAllChildren().keys()) == 5) self.assertTrue(len(res.GetLeaves().keys()) == 3) def test2(self): m = Chem.MolFromSmiles('CCCOCCC') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(res.children == {}) def test3(self): allNodes = {} m = Chem.MolFromSmiles('c1ccccc1-c1ncccc1') res = RecapDecompose(m, allNodes=allNodes) self.assertTrue(res) self.assertTrue(len(res.children.keys()) == 2) self.assertTrue(len(allNodes.keys()) == 3) m = Chem.MolFromSmiles('COc1ccccc1-c1ncccc1') res = RecapDecompose(m, allNodes=allNodes) self.assertTrue(res) self.assertTrue(len(res.children.keys()) == 2) # we get two more nodes from that: self.assertTrue(len(allNodes.keys()) == 5) self.assertTrue('[*]c1ccccc1OC' in allNodes) self.assertTrue('[*]c1ccccc1' in allNodes) m = Chem.MolFromSmiles('C1CC1Oc1ccccc1-c1ncccc1') res = RecapDecompose(m, allNodes=allNodes) self.assertTrue(res) self.assertTrue(len(res.children.keys()) == 4) self.assertTrue(len(allNodes.keys()) == 10) def testSFNetIssue1801871(self): m = Chem.MolFromSmiles('c1ccccc1OC(Oc1ccccc1)Oc1ccccc1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertFalse('[*]C([*])[*]' in ks) self.assertTrue('[*]c1ccccc1' in ks) self.assertTrue('[*]C([*])Oc1ccccc1' in ks) def testSFNetIssue1804418(self): m = Chem.MolFromSmiles('C1CCCCN1CCCC') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]N1CCCCC1' in ks) self.assertTrue('[*]CCCC' in ks) def testMinFragmentSize(self): m = Chem.MolFromSmiles('CCCOCCC') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(res.children == {}) res = RecapDecompose(m, minFragmentSize=3) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 1) ks = res.GetLeaves().keys() self.assertTrue('[*]CCC' in ks) m = Chem.MolFromSmiles('CCCOCC') res = RecapDecompose(m, minFragmentSize=3) self.assertTrue(res) self.assertTrue(res.children == {}) m = Chem.MolFromSmiles('CCCOCCOC') res = RecapDecompose(m, minFragmentSize=2) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]CCC' in ks) ks = res.GetLeaves().keys() self.assertTrue('[*]CCOC' in ks) def testAmideRxn(self): m = Chem.MolFromSmiles('C1CC1C(=O)NC1OC1') res = RecapDecompose(m, onlyUseReactions=[1]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]C(=O)C1CC1' in ks) self.assertTrue('[*]NC1CO1' in ks) m = Chem.MolFromSmiles('C1CC1C(=O)N(C)C1OC1') res = RecapDecompose(m, onlyUseReactions=[1]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]C(=O)C1CC1' in ks) self.assertTrue('[*]N(C)C1CO1' in ks) m = Chem.MolFromSmiles('C1CC1C(=O)n1cccc1') res = RecapDecompose(m, onlyUseReactions=[1]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]C(=O)C1CC1' in ks) self.assertTrue('[*]n1cccc1' in ks) m = Chem.MolFromSmiles('C1CC1C(=O)CC1OC1') res = RecapDecompose(m, onlyUseReactions=[1]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) m = Chem.MolFromSmiles('C1CCC(=O)NC1') res = RecapDecompose(m, onlyUseReactions=[1]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) m = Chem.MolFromSmiles('CC(=O)NC') res = RecapDecompose(m, onlyUseReactions=[1]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() m = Chem.MolFromSmiles('CC(=O)N') res = RecapDecompose(m, onlyUseReactions=[1]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) m = Chem.MolFromSmiles('C(=O)NCCNC(=O)CC') res = RecapDecompose(m, onlyUseReactions=[1]) self.assertTrue(res) self.assertTrue(len(res.children) == 4) self.assertTrue(len(res.GetLeaves()) == 3) def testEsterRxn(self): m = Chem.MolFromSmiles('C1CC1C(=O)OC1OC1') res = RecapDecompose(m, onlyUseReactions=[2]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]C(=O)C1CC1' in ks) self.assertTrue('[*]OC1CO1' in ks) m = Chem.MolFromSmiles('C1CC1C(=O)CC1OC1') res = RecapDecompose(m, onlyUseReactions=[2]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) m = Chem.MolFromSmiles('C1CCC(=O)OC1') res = RecapDecompose(m, onlyUseReactions=[2]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) def testUreaRxn(self): m = Chem.MolFromSmiles('C1CC1NC(=O)NC1OC1') res = RecapDecompose(m, onlyUseReactions=[0]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]NC1CC1' in ks) self.assertTrue('[*]NC1CO1' in ks) m = Chem.MolFromSmiles('C1CC1NC(=O)N(C)C1OC1') res = RecapDecompose(m, onlyUseReactions=[0]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]NC1CC1' in ks) self.assertTrue('[*]N(C)C1CO1' in ks) m = Chem.MolFromSmiles('C1CCNC(=O)NC1C') res = RecapDecompose(m, onlyUseReactions=[0]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) m = Chem.MolFromSmiles('c1cccn1C(=O)NC1OC1') res = RecapDecompose(m, onlyUseReactions=[0]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]n1cccc1' in ks) self.assertTrue('[*]NC1CO1' in ks) m = Chem.MolFromSmiles('c1cccn1C(=O)n1c(C)ccc1') res = RecapDecompose(m, onlyUseReactions=[0]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]n1cccc1C' in ks) def testAmineRxn(self): m = Chem.MolFromSmiles('C1CC1N(C1NC1)C1OC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 3) ks = res.GetLeaves().keys() self.assertTrue('[*]C1CC1' in ks) self.assertTrue('[*]C1CO1' in ks) self.assertTrue('[*]C1CN1' in ks) m = Chem.MolFromSmiles('c1ccccc1N(C1NC1)C1OC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 3) ks = res.GetLeaves().keys() self.assertTrue('[*]c1ccccc1' in ks) self.assertTrue('[*]C1CO1' in ks) self.assertTrue('[*]C1CN1' in ks) m = Chem.MolFromSmiles('c1ccccc1N(c1ncccc1)C1OC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 3) ks = res.GetLeaves().keys() self.assertTrue('[*]c1ccccc1' in ks) self.assertTrue('[*]c1ccccn1' in ks) self.assertTrue('[*]C1CO1' in ks) m = Chem.MolFromSmiles('c1ccccc1N(c1ncccc1)c1ccco1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 3) ks = res.GetLeaves().keys() self.assertTrue('[*]c1ccccc1' in ks) self.assertTrue('[*]c1ccccn1' in ks) self.assertTrue('[*]c1ccco1' in ks) m = Chem.MolFromSmiles('C1CCCCN1C1CC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]N1CCCCC1' in ks) self.assertTrue('[*]C1CC1' in ks) m = Chem.MolFromSmiles('C1CCC2N1CC2') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) def testEtherRxn(self): m = Chem.MolFromSmiles('C1CC1OC1OC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]C1CC1' in ks) self.assertTrue('[*]C1CO1' in ks) m = Chem.MolFromSmiles('C1CCCCO1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) m = Chem.MolFromSmiles('c1ccccc1OC1OC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]c1ccccc1' in ks) self.assertTrue('[*]C1CO1' in ks) m = Chem.MolFromSmiles('c1ccccc1Oc1ncccc1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]c1ccccc1' in ks) self.assertTrue('[*]c1ccccn1' in ks) def testOlefinRxn(self): m = Chem.MolFromSmiles('ClC=CBr') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]CCl' in ks) self.assertTrue('[*]CBr' in ks) m = Chem.MolFromSmiles('C1CC=CC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) def testAromNAliphCRxn(self): m = Chem.MolFromSmiles('c1cccn1CCCC') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]n1cccc1' in ks) self.assertTrue('[*]CCCC' in ks) m = Chem.MolFromSmiles('c1ccc2n1CCCC2') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) def testLactamNAliphCRxn(self): m = Chem.MolFromSmiles('C1CC(=O)N1CCCC') res = RecapDecompose(m, onlyUseReactions=[8]) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]N1CCC1=O' in ks) self.assertTrue('[*]CCCC' in ks) m = Chem.MolFromSmiles('O=C1CC2N1CCCC2') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) def testAromCAromCRxn(self): m = Chem.MolFromSmiles('c1ccccc1c1ncccc1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]c1ccccc1' in ks) self.assertTrue('[*]c1ccccn1' in ks) m = Chem.MolFromSmiles('c1ccccc1C1CC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) def testAromNAromCRxn(self): m = Chem.MolFromSmiles('c1cccn1c1ccccc1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]n1cccc1' in ks) self.assertTrue('[*]c1ccccc1' in ks) def testSulfonamideRxn(self): m = Chem.MolFromSmiles('CCCNS(=O)(=O)CC') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]NCCC' in ks) self.assertTrue('[*]S(=O)(=O)CC' in ks) m = Chem.MolFromSmiles('c1cccn1S(=O)(=O)CC') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) ks = res.GetLeaves().keys() self.assertTrue('[*]n1cccc1' in ks) self.assertTrue('[*]S(=O)(=O)CC' in ks) m = Chem.MolFromSmiles('C1CNS(=O)(=O)CC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) def testSFNetIssue1881803(self): m = Chem.MolFromSmiles('c1ccccc1n1cccc1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) m = Chem.MolFromSmiles('c1ccccc1[n+]1ccccc1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) m = Chem.MolFromSmiles('C1CC1NC(=O)CC') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) m = Chem.MolFromSmiles('C1CC1[NH+]C(=O)CC') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) m = Chem.MolFromSmiles('C1CC1NC(=O)NC1CCC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 2) m = Chem.MolFromSmiles('C1CC1[NH+]C(=O)[NH+]C1CCC1') res = RecapDecompose(m) self.assertTrue(res) self.assertTrue(len(res.GetLeaves()) == 0) unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Recap.py", "copies": "1", "size": "21520", "license": "bsd-3-clause", "hash": 7823899628298728000, "line_mean": 34.5115511551, "line_max": 130, "alpha_frac": 0.6096654275, "autogenerated": false, "ratio": 2.908108108108108, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40177735356081085, "avg_score": null, "num_lines": null }
from rdkit import Chem from rdkit import RDConfig import numpy import math import sys import copy import pprint from rdkit.six import cmp periodicTable=Chem.GetPeriodicTable() class Font(object): face='sans' size='12' weight='normal' name=None def __init__(self,face=None,size=None,name=None,weight=None): if face: self.face=face if size: self.size=size if name: self.name=name if weight: self.weight=weight class DrawingOptions(object): dotsPerAngstrom= 30 useFraction= 0.85 atomLabelFontFace= "sans" atomLabelFontSize= 12 atomLabelMinFontSize= 7 bondLineWidth= 1.2 dblBondOffset= .25 dblBondLengthFrac= .8 defaultColor= (1,0,0) selectColor= (1,0,0) bgColor = (1,1,1) colorBonds= True noCarbonSymbols= True includeAtomNumbers= False atomNumberOffset= 0 radicalSymbol= u'\u2219' dash= (4,4) wedgeDashedBonds= True showUnknownDoubleBonds= True # used to adjust overall scaling for molecules that have been laid out with non-standard # bond lengths coordScale= 1.0 elemDict={ 1:(0.55,0.55,0.55), 7:(0,0,1), 8:(1,0,0), 9:(.2,.8,.8), 15:(1,.5,0), 16:(.8,.8,0), 17:(0,.8,0), 35:(.5,.3,.1), 53:(.63,.12,.94), 0:(.5,.5,.5), } class MolDrawing(object): atomPs = None canvas = None canvasSize = None def __init__(self,canvas=None, drawingOptions=None): self.canvas = canvas if canvas: self.canvasSize=canvas.size self.atomPs = {} if drawingOptions is None: self.drawingOptions=DrawingOptions() else: self.drawingOptions=drawingOptions self.boundingBoxes = {} if self.drawingOptions.bgColor is not None: self.canvas.addCanvasPolygon(((0,0), (canvas.size[0],0), (canvas.size[0],canvas.size[1]), (0,canvas.size[1])), color=self.drawingOptions.bgColor, fill=True,stroke=False) def transformPoint(self,pos): res = [0,0] res[0] = (pos[0] + self.molTrans[0])*self.currDotsPerAngstrom*self.drawingOptions.useFraction + self.drawingTrans[0] res[1] = self.canvasSize[1]-((pos[1] + self.molTrans[1])*self.currDotsPerAngstrom*self.drawingOptions.useFraction + \ self.drawingTrans[1]) return res def _getBondOffset(self,p1,p2): # get the vector between the points: dx = p2[0]-p1[0] dy = p2[1]-p1[1] # figure out the angle and the perpendicular: ang = math.atan2(dy,dx) perp = ang + math.pi/2. # here's the offset for the parallel bond: offsetX = math.cos(perp)*self.drawingOptions.dblBondOffset*self.currDotsPerAngstrom offsetY = math.sin(perp)*self.drawingOptions.dblBondOffset*self.currDotsPerAngstrom return perp,offsetX,offsetY def _getOffsetBondPts(self,p1,p2, offsetX,offsetY, lenFrac=None): if not lenFrac: lenFrac = self.drawingOptions.dblBondLengthFrac dx = p2[0]-p1[0] dy = p2[1]-p1[1] # ---- # now figure out where to start and end it: # offset the start point: fracP1 = p1[0]+offsetX,p1[1]+offsetY # now move a portion of the way along the line to the neighbor: frac = (1.-lenFrac)/2 fracP1 = fracP1[0]+dx*frac,\ fracP1[1]+dy*frac fracP2 = fracP1[0]+dx*lenFrac,\ fracP1[1]+dy*lenFrac return fracP1,fracP2 def _offsetDblBond(self,p1,p2,bond,a1,a2,conf,dir=1, lenFrac=None): perp,offsetX,offsetY = self._getBondOffset(p1,p2) offsetX = offsetX*dir offsetY = offsetY*dir # if we're a ring bond, we may need to flip over to the other side: if bond.IsInRing(): bondIdx = bond.GetIdx() a1Idx = a1.GetIdx() a2Idx = a2.GetIdx() # find a ring bond from a1 to an atom other than a2: for otherBond in a1.GetBonds(): if otherBond.GetIdx()!=bondIdx and \ otherBond.IsInRing(): sharedRing=False for ring in self.bondRings: if bondIdx in ring and otherBond.GetIdx() in ring: sharedRing=True break if not sharedRing: continue a3 = otherBond.GetOtherAtom(a1) if a3.GetIdx() != a2Idx: p3 = self.transformPoint(conf.GetAtomPosition(a3.GetIdx())*self.drawingOptions.coordScale) dx2 = p3[0] - p1[0] dy2 = p3[1] - p1[1] dotP = dx2*offsetX + dy2*offsetY if dotP < 0: perp += math.pi offsetX = math.cos(perp)*self.drawingOptions.dblBondOffset*self.currDotsPerAngstrom offsetY = math.sin(perp)*self.drawingOptions.dblBondOffset*self.currDotsPerAngstrom fracP1,fracP2 = self._getOffsetBondPts(p1,p2, offsetX,offsetY, lenFrac=lenFrac) return fracP1,fracP2 def _getBondAttachmentCoordinates(self, p1, p2, labelSize): newpos = [None, None] if labelSize != None: labelSizeOffset = [labelSize[0][0]/2 + (cmp(p2[0], p1[0]) * labelSize[0][2]), labelSize[0][1]/2] if p1[1] == p2[1]: newpos[0] = p1[0] + cmp(p2[0], p1[0]) * labelSizeOffset[0] else: if abs(labelSizeOffset[1] * (p2[0] - p1[0]) / (p2[1] - p1[1])) < labelSizeOffset[0]: newpos[0] = p1[0] + cmp(p2[0], p1[0]) * abs(labelSizeOffset[1] * (p2[0] - p1[0]) / (p2[1] - p1[1])) else: newpos[0] = p1[0] + cmp(p2[0], p1[0]) * labelSizeOffset[0] if p1[0] == p2[0]: newpos[1] = p1[1] + cmp(p2[1], p1[1]) * labelSizeOffset[1] else: if abs(labelSizeOffset[0] * (p1[1] - p2[1]) / (p2[0] - p1[0])) < labelSizeOffset[1]: newpos[1] = p1[1] + cmp(p2[1], p1[1]) * abs(labelSizeOffset[0] * (p1[1] - p2[1]) / (p2[0] - p1[0])) else: newpos[1] = p1[1] + cmp(p2[1], p1[1]) * labelSizeOffset[1] else: newpos = copy.deepcopy(p1) return newpos def _drawWedgedBond(self,bond,pos,nbrPos, width=None,color=None, dash=None): if width is None: width = self.drawingOptions.bondLineWidth if color is None: color = self.drawingOptions.defaultColor perp,offsetX,offsetY = self._getBondOffset(pos,nbrPos) offsetX *=.75 offsetY *=.75 poly = ((pos[0],pos[1]), (nbrPos[0]+offsetX,nbrPos[1]+offsetY), (nbrPos[0]-offsetX,nbrPos[1]-offsetY)) #canvas.drawPolygon(poly,edgeColor=color,edgeWidth=1,fillColor=color,closed=1) if not dash: self.canvas.addCanvasPolygon(poly,color=color) elif self.drawingOptions.wedgeDashedBonds and self.canvas.addCanvasDashedWedge: self.canvas.addCanvasDashedWedge(poly[0],poly[1],poly[2],color=color) else: self.canvas.addCanvasLine(pos,nbrPos,linewidth=width*2,color=color, dashes=dash) def _drawBond(self,bond,atom,nbr,pos,nbrPos,conf, width=None,color=None,color2=None,labelSize1=None,labelSize2=None): if width is None: width = self.drawingOptions.bondLineWidth if color is None: color = self.drawingOptions.defaultColor p1_raw = copy.deepcopy(pos) p2_raw = copy.deepcopy(nbrPos) newpos = self._getBondAttachmentCoordinates(p1_raw, p2_raw, labelSize1) newnbrPos = self._getBondAttachmentCoordinates(p2_raw, p1_raw, labelSize2) bType=bond.GetBondType() if bType == Chem.BondType.SINGLE: bDir = bond.GetBondDir() if bDir in (Chem.BondDir.BEGINWEDGE,Chem.BondDir.BEGINDASH): # if the bond is "backwards", change the drawing direction: if bond.GetBeginAtom().GetChiralTag() in (Chem.ChiralType.CHI_TETRAHEDRAL_CW, Chem.ChiralType.CHI_TETRAHEDRAL_CCW): p1,p2 = newpos,newnbrPos wcolor=color else: p2,p1 = newpos,newnbrPos if color2 is not None: wcolor=color2 else: wcolor=self.drawingOptions.defaultColor if bDir==Chem.BondDir.BEGINWEDGE: self._drawWedgedBond(bond,p1,p2,color=wcolor,width=width) elif bDir==Chem.BondDir.BEGINDASH: self._drawWedgedBond(bond,p1,p2,color=wcolor,width=width, dash=self.drawingOptions.dash) else: self.canvas.addCanvasLine(newpos, newnbrPos, linewidth=width, color=color, color2=color2) elif bType == Chem.BondType.DOUBLE: crossBond = (self.drawingOptions.showUnknownDoubleBonds and \ bond.GetStereo() == Chem.BondStereo.STEREOANY) if not crossBond and \ ( bond.IsInRing() or (atom.GetDegree()!=1 and bond.GetOtherAtom(atom).GetDegree()!=1) ): self.canvas.addCanvasLine(newpos,newnbrPos,linewidth=width,color=color,color2=color2) fp1,fp2 = self._offsetDblBond(newpos,newnbrPos,bond,atom,nbr,conf) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2) else: fp1,fp2 = self._offsetDblBond(newpos,newnbrPos,bond,atom,nbr,conf,dir=.5, lenFrac=1.0) fp3,fp4 = self._offsetDblBond(newpos,newnbrPos,bond,atom,nbr,conf,dir=-.5, lenFrac=1.0) if crossBond: fp2,fp4=fp4,fp2 self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2) self.canvas.addCanvasLine(fp3,fp4,linewidth=width,color=color,color2=color2) elif bType == Chem.BondType.AROMATIC: self.canvas.addCanvasLine(newpos,newnbrPos,linewidth=width,color=color,color2=color2) fp1,fp2 = self._offsetDblBond(newpos,newnbrPos,bond,atom,nbr,conf) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2, dash=self.drawingOptions.dash) elif bType == Chem.BondType.TRIPLE: self.canvas.addCanvasLine(newpos,newnbrPos,linewidth=width,color=color,color2=color2) fp1,fp2 = self._offsetDblBond(newpos,newnbrPos,bond,atom,nbr,conf) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2) fp1,fp2 = self._offsetDblBond(newpos,newnbrPos,bond,atom,nbr,conf,dir=-1) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2) else: self.canvas.addCanvasLine(newpos, newnbrPos, linewidth=width, color=color, color2=color2, dash=(1,2)) def scaleAndCenter(self,mol,conf,coordCenter=False,canvasSize=None,ignoreHs=False): if canvasSize is None: canvasSize=self.canvasSize xAccum = 0 yAccum = 0 minX = 1e8 minY = 1e8 maxX = -1e8 maxY = -1e8 nAts = mol.GetNumAtoms() for i in range(nAts): if ignoreHs and mol.GetAtomWithIdx(i).GetAtomicNum()==1: continue pos = conf.GetAtomPosition(i)*self.drawingOptions.coordScale xAccum += pos[0] yAccum += pos[1] minX = min(minX,pos[0]) minY = min(minY,pos[1]) maxX = max(maxX,pos[0]) maxY = max(maxY,pos[1]) dx = abs(maxX-minX) dy = abs(maxY-minY) xSize = dx*self.currDotsPerAngstrom ySize = dy*self.currDotsPerAngstrom if coordCenter: molTrans = -xAccum/nAts,-yAccum/nAts else: molTrans = -(minX+(maxX-minX)/2),-(minY+(maxY-minY)/2) self.molTrans = molTrans if xSize>=.95*canvasSize[0]: scale = .9*canvasSize[0]/xSize xSize*=scale ySize*=scale self.currDotsPerAngstrom*=scale self.currAtomLabelFontSize = max(self.currAtomLabelFontSize*scale, self.drawingOptions.atomLabelMinFontSize) if ySize>=.95*canvasSize[1]: scale = .9*canvasSize[1]/ySize xSize*=scale ySize*=scale self.currDotsPerAngstrom*=scale self.currAtomLabelFontSize = max(self.currAtomLabelFontSize*scale, self.drawingOptions.atomLabelMinFontSize) drawingTrans = canvasSize[0]/2,canvasSize[1]/2 self.drawingTrans = drawingTrans def _drawLabel(self,label,pos,baseOffset,font,color=None,**kwargs): if color is None: color = self.drawingOptions.defaultColor x1 = pos[0] y1 = pos[1] labelP = x1,y1 labelSize = self.canvas.addCanvasText(label,(x1,y1,baseOffset),font,color,**kwargs) return labelSize def AddMol(self,mol,centerIt=True,molTrans=None,drawingTrans=None, highlightAtoms=[],confId=-1,flagCloseContactsDist=2, highlightMap=None, ignoreHs=False,highlightBonds=[],**kwargs): """Set the molecule to be drawn. Parameters: hightlightAtoms -- list of atoms to highlight (default []) highlightMap -- dictionary of (atom, color) pairs (default None) Notes: - specifying centerIt will cause molTrans and drawingTrans to be ignored """ conf = mol.GetConformer(confId) if 'coordScale' in kwargs: self.drawingOptions.coordScale=kwargs['coordScale'] self.currDotsPerAngstrom=self.drawingOptions.dotsPerAngstrom self.currAtomLabelFontSize=self.drawingOptions.atomLabelFontSize if centerIt: self.scaleAndCenter(mol,conf,ignoreHs=ignoreHs) else: if molTrans is None: molTrans = (0,0) self.molTrans = molTrans if drawingTrans is None: drawingTrans = (0,0) self.drawingTrans = drawingTrans font = Font(face=self.drawingOptions.atomLabelFontFace,size=self.currAtomLabelFontSize) obds=None if not mol.HasProp('_drawingBondsWedged'): # this is going to modify the molecule, get ready to undo that obds=[x.GetBondDir() for x in mol.GetBonds()] Chem.WedgeMolBonds(mol,conf) includeAtomNumbers = kwargs.get('includeAtomNumbers',self.drawingOptions.includeAtomNumbers) self.atomPs[mol] = {} self.boundingBoxes[mol] = [0]*4 self.activeMol = mol self.bondRings = mol.GetRingInfo().BondRings() labelSizes = {} for atom in mol.GetAtoms(): labelSizes[atom.GetIdx()] = None if ignoreHs and atom.GetAtomicNum()==1: drawAtom=False else: drawAtom=True idx = atom.GetIdx() pos = self.atomPs[mol].get(idx,None) if pos is None: pos = self.transformPoint(conf.GetAtomPosition(idx)*self.drawingOptions.coordScale) self.atomPs[mol][idx] = pos if drawAtom: self.boundingBoxes[mol][0]=min(self.boundingBoxes[mol][0],pos[0]) self.boundingBoxes[mol][1]=min(self.boundingBoxes[mol][1],pos[1]) self.boundingBoxes[mol][2]=max(self.boundingBoxes[mol][2],pos[0]) self.boundingBoxes[mol][3]=max(self.boundingBoxes[mol][3],pos[1]) if not drawAtom: continue nbrSum = [0,0] for bond in atom.GetBonds(): nbr = bond.GetOtherAtom(atom) if ignoreHs and nbr.GetAtomicNum()==1: continue nbrIdx = nbr.GetIdx() if nbrIdx > idx: nbrPos = self.atomPs[mol].get(nbrIdx,None) if nbrPos is None: nbrPos = self.transformPoint(conf.GetAtomPosition(nbrIdx)*self.drawingOptions.coordScale) self.atomPs[mol][nbrIdx] = nbrPos self.boundingBoxes[mol][0]=min(self.boundingBoxes[mol][0],nbrPos[0]) self.boundingBoxes[mol][1]=min(self.boundingBoxes[mol][1],nbrPos[1]) self.boundingBoxes[mol][2]=max(self.boundingBoxes[mol][2],nbrPos[0]) self.boundingBoxes[mol][3]=max(self.boundingBoxes[mol][3],nbrPos[1]) else: nbrPos = self.atomPs[mol][nbrIdx] nbrSum[0] += nbrPos[0]-pos[0] nbrSum[1] += nbrPos[1]-pos[1] iso = atom.GetIsotope() labelIt= not self.drawingOptions.noCarbonSymbols or \ atom.GetAtomicNum()!=6 or \ atom.GetFormalCharge()!=0 or \ atom.GetNumRadicalElectrons() or \ includeAtomNumbers or \ iso or \ atom.HasProp('molAtomMapNumber') or \ atom.GetDegree()==0 orient='' if labelIt: baseOffset = 0 if includeAtomNumbers: symbol = str(atom.GetIdx()) symbolLength = len(symbol) else: base = atom.GetSymbol() symbolLength = len(base) if not atom.HasQuery(): nHs = atom.GetTotalNumHs() else: nHs = 0 if nHs>0: if nHs>1: hs='H<sub>%d</sub>'%nHs symbolLength += 1 + len(str(nHs)) else: hs ='H' symbolLength += 1 else: hs = '' chg = atom.GetFormalCharge() if chg!=0: if chg==1: chg = '+' elif chg==-1: chg = '-' elif chg>1: chg = '+%d'%chg elif chg<-1: chg = '-%d'%chg symbolLength += len(chg) else: chg = '' if chg: chg = '<sup>%s</sup>'%chg if atom.GetNumRadicalElectrons(): rad = self.drawingOptions.radicalSymbol*atom.GetNumRadicalElectrons() rad = '<sup>%s</sup>'%rad symbolLength += atom.GetNumRadicalElectrons() else: rad = '' isotope='' isotopeLength = 0 if iso: isotope='<sup>%d</sup>'%atom.GetIsotope() isotopeLength = len(str(atom.GetIsotope())) symbolLength += isotopeLength mapNum='' mapNumLength = 0 if atom.HasProp('molAtomMapNumber'): mapNum=':'+atom.GetProp('molAtomMapNumber') mapNumLength = 1 + len(str(atom.GetProp('molAtomMapNumber'))) symbolLength += mapNumLength deg = atom.GetDegree() # This should be done in a better way in the future: # 'baseOffset' should be determined by getting the size of 'isotope' and the size of 'base', or the size of 'mapNum' and the size of 'base' # (depending on 'deg' and 'nbrSum[0]') in order to determine the exact position of the base if deg==0: if periodicTable.GetElementSymbol(atom.GetAtomicNum()) in ('O','S','Se','Te','F','Cl','Br','I','At'): symbol = '%s%s%s%s%s%s'%(hs,isotope,base,chg,rad,mapNum) else: symbol = '%s%s%s%s%s%s'%(isotope,base,hs,chg,rad,mapNum) elif deg>1 or nbrSum[0]<1: symbol = '%s%s%s%s%s%s'%(isotope,base,hs,chg,rad,mapNum) baseOffset = 0.5 - (isotopeLength + len(base) / 2.) / symbolLength else: symbol = '%s%s%s%s%s%s'%(rad,chg,hs,isotope,base,mapNum) baseOffset = -0.5 + (mapNumLength + len(base) / 2.) / symbolLength if deg==1: if abs(nbrSum[1])>1: islope=nbrSum[0]/abs(nbrSum[1]) else: islope=nbrSum[0] if abs(islope)>.3: if islope>0: orient='W' else: orient='E' elif abs(nbrSum[1])>10: if nbrSum[1]>0: orient='N' else : orient='S' else: orient = 'C' if highlightMap and idx in highlightMap: color = highlightMap[idx] elif highlightAtoms and idx in highlightAtoms: color = self.drawingOptions.selectColor else: color = self.drawingOptions.elemDict.get(atom.GetAtomicNum(),(0,0,0)) labelSize = self._drawLabel(symbol, pos, baseOffset, font, color=color,orientation=orient) labelSizes[atom.GetIdx()] = [labelSize, orient] for bond in mol.GetBonds(): atom, idx = bond.GetBeginAtom(), bond.GetBeginAtomIdx() nbr, nbrIdx = bond.GetEndAtom(), bond.GetEndAtomIdx() pos = self.atomPs[mol].get(idx,None) nbrPos = self.atomPs[mol].get(nbrIdx,None) if highlightBonds and bond.GetIdx() in highlightBonds: width=2.0*self.drawingOptions.bondLineWidth color = self.drawingOptions.selectColor color2 = self.drawingOptions.selectColor elif highlightAtoms and idx in highlightAtoms and nbrIdx in highlightAtoms: width=2.0*self.drawingOptions.bondLineWidth color = self.drawingOptions.selectColor color2 = self.drawingOptions.selectColor elif highlightMap is not None and idx in highlightMap and nbrIdx in highlightMap: width=2.0*self.drawingOptions.bondLineWidth color = highlightMap[idx] color2 = highlightMap[nbrIdx] else: width=self.drawingOptions.bondLineWidth if self.drawingOptions.colorBonds: color = self.drawingOptions.elemDict.get(atom.GetAtomicNum(),(0,0,0)) color2 = self.drawingOptions.elemDict.get(nbr.GetAtomicNum(),(0,0,0)) else: color = self.drawingOptions.defaultColor color2= color self._drawBond(bond,atom,nbr,pos,nbrPos,conf, color=color,width=width,color2=color2,labelSize1=labelSizes[idx],labelSize2=labelSizes[nbrIdx]) # if we modified the bond wedging state, undo those changes now if obds: for i,d in enumerate(obds): mol.GetBondWithIdx(i).SetBondDir(d) if flagCloseContactsDist>0: tol = flagCloseContactsDist*flagCloseContactsDist for i,atomi in enumerate(mol.GetAtoms()): pi = numpy.array(self.atomPs[mol][i]) for j in range(i+1,mol.GetNumAtoms()): pj = numpy.array(self.atomPs[mol][j]) d = pj-pi dist2 = d[0]*d[0]+d[1]*d[1] if dist2<=tol: self.canvas.addCanvasPolygon(((pi[0]-2*flagCloseContactsDist, pi[1]-2*flagCloseContactsDist), (pi[0]+2*flagCloseContactsDist, pi[1]-2*flagCloseContactsDist), (pi[0]+2*flagCloseContactsDist, pi[1]+2*flagCloseContactsDist), (pi[0]-2*flagCloseContactsDist, pi[1]+2*flagCloseContactsDist)), color=(1.,0,0), fill=False,stroke=True)
{ "repo_name": "strets123/rdkit", "path": "rdkit/Chem/Draw/MolDrawing.py", "copies": "3", "size": "22730", "license": "bsd-3-clause", "hash": 2802591211623907000, "line_mean": 37.265993266, "line_max": 149, "alpha_frac": 0.5934007919, "autogenerated": false, "ratio": 3.2443619754496145, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.03785798393218382, "num_lines": 594 }
from rdkit import Chem from rdkit import RDConfig import numpy import math import sys import copy import pprint from rdkit.six import cmp periodicTable = Chem.GetPeriodicTable() class Font(object): face = 'sans' size = '12' weight = 'normal' name = None def __init__(self, face=None, size=None, name=None, weight=None): if face: self.face = face if size: self.size = size if name: self.name = name if weight: self.weight = weight class DrawingOptions(object): dotsPerAngstrom = 30 useFraction = 0.85 atomLabelFontFace = "sans" atomLabelFontSize = 12 atomLabelMinFontSize = 7 atomLabelDeuteriumTritium = False bondLineWidth = 1.2 dblBondOffset = .25 dblBondLengthFrac = .8 defaultColor = (1, 0, 0) selectColor = (1, 0, 0) bgColor = (1, 1, 1) colorBonds = True noCarbonSymbols = True includeAtomNumbers = False atomNumberOffset = 0 radicalSymbol = u'\u2219' dash = (4, 4) wedgeDashedBonds = True showUnknownDoubleBonds = True # used to adjust overall scaling for molecules that have been laid out with non-standard # bond lengths coordScale = 1.0 elemDict = { 1: (0.55, 0.55, 0.55), 7: (0, 0, 1), 8: (1, 0, 0), 9: (.2, .8, .8), 15: (1, .5, 0), 16: (.8, .8, 0), 17: (0, .8, 0), 35: (.5, .3, .1), 53: (.63, .12, .94), 0: (.5, .5, .5), } class MolDrawing(object): atomPs = None canvas = None canvasSize = None def __init__(self, canvas=None, drawingOptions=None): self.canvas = canvas if canvas: self.canvasSize = canvas.size self.atomPs = {} if drawingOptions is None: self.drawingOptions = DrawingOptions() else: self.drawingOptions = drawingOptions self.boundingBoxes = {} if self.drawingOptions.bgColor is not None: self.canvas.addCanvasPolygon(((0, 0), (canvas.size[0], 0), (canvas.size[0], canvas.size[1]), (0, canvas.size[1])), color=self.drawingOptions.bgColor, fill=True, stroke=False) def transformPoint(self, pos): res = [0, 0] res[0] = (pos[0] + self.molTrans[0] ) * self.currDotsPerAngstrom * self.drawingOptions.useFraction + self.drawingTrans[0] res[1] = self.canvasSize[1]-((pos[1] + self.molTrans[1])*self.currDotsPerAngstrom*self.drawingOptions.useFraction + \ self.drawingTrans[1]) return res def _getBondOffset(self, p1, p2): # get the vector between the points: dx = p2[0] - p1[0] dy = p2[1] - p1[1] # figure out the angle and the perpendicular: ang = math.atan2(dy, dx) perp = ang + math.pi / 2. # here's the offset for the parallel bond: offsetX = math.cos(perp) * self.drawingOptions.dblBondOffset * self.currDotsPerAngstrom offsetY = math.sin(perp) * self.drawingOptions.dblBondOffset * self.currDotsPerAngstrom return perp, offsetX, offsetY def _getOffsetBondPts(self, p1, p2, offsetX, offsetY, lenFrac=None): if not lenFrac: lenFrac = self.drawingOptions.dblBondLengthFrac dx = p2[0] - p1[0] dy = p2[1] - p1[1] # ---- # now figure out where to start and end it: # offset the start point: fracP1 = p1[0] + offsetX, p1[1] + offsetY # now move a portion of the way along the line to the neighbor: frac = (1. - lenFrac) / 2 fracP1 = fracP1[0]+dx*frac,\ fracP1[1]+dy*frac fracP2 = fracP1[0]+dx*lenFrac,\ fracP1[1]+dy*lenFrac return fracP1, fracP2 def _offsetDblBond(self, p1, p2, bond, a1, a2, conf, dir=1, lenFrac=None): perp, offsetX, offsetY = self._getBondOffset(p1, p2) offsetX = offsetX * dir offsetY = offsetY * dir # if we're a ring bond, we may need to flip over to the other side: if bond.IsInRing(): bondIdx = bond.GetIdx() a1Idx = a1.GetIdx() a2Idx = a2.GetIdx() # find a ring bond from a1 to an atom other than a2: for otherBond in a1.GetBonds(): if otherBond.GetIdx()!=bondIdx and \ otherBond.IsInRing(): sharedRing = False for ring in self.bondRings: if bondIdx in ring and otherBond.GetIdx() in ring: sharedRing = True break if not sharedRing: continue a3 = otherBond.GetOtherAtom(a1) if a3.GetIdx() != a2Idx: p3 = self.transformPoint( conf.GetAtomPosition(a3.GetIdx()) * self.drawingOptions.coordScale) dx2 = p3[0] - p1[0] dy2 = p3[1] - p1[1] dotP = dx2 * offsetX + dy2 * offsetY if dotP < 0: perp += math.pi offsetX = math.cos( perp) * self.drawingOptions.dblBondOffset * self.currDotsPerAngstrom offsetY = math.sin( perp) * self.drawingOptions.dblBondOffset * self.currDotsPerAngstrom fracP1, fracP2 = self._getOffsetBondPts(p1, p2, offsetX, offsetY, lenFrac=lenFrac) return fracP1, fracP2 def _getBondAttachmentCoordinates(self, p1, p2, labelSize): newpos = [None, None] if labelSize != None: labelSizeOffset = [labelSize[0][0] / 2 + (cmp(p2[0], p1[0]) * labelSize[0][2]), labelSize[0][1] / 2] if p1[1] == p2[1]: newpos[0] = p1[0] + cmp(p2[0], p1[0]) * labelSizeOffset[0] else: if abs(labelSizeOffset[1] * (p2[0] - p1[0]) / (p2[1] - p1[1])) < labelSizeOffset[0]: newpos[0] = p1[0] + cmp(p2[0], p1[0]) * abs(labelSizeOffset[1] * (p2[0] - p1[0]) / (p2[1] - p1[1])) else: newpos[0] = p1[0] + cmp(p2[0], p1[0]) * labelSizeOffset[0] if p1[0] == p2[0]: newpos[1] = p1[1] + cmp(p2[1], p1[1]) * labelSizeOffset[1] else: if abs(labelSizeOffset[0] * (p1[1] - p2[1]) / (p2[0] - p1[0])) < labelSizeOffset[1]: newpos[1] = p1[1] + cmp(p2[1], p1[1]) * abs(labelSizeOffset[0] * (p1[1] - p2[1]) / (p2[0] - p1[0])) else: newpos[1] = p1[1] + cmp(p2[1], p1[1]) * labelSizeOffset[1] else: newpos = copy.deepcopy(p1) return newpos def _drawWedgedBond(self, bond, pos, nbrPos, width=None, color=None, dash=None): if width is None: width = self.drawingOptions.bondLineWidth if color is None: color = self.drawingOptions.defaultColor perp, offsetX, offsetY = self._getBondOffset(pos, nbrPos) offsetX *= .75 offsetY *= .75 poly = ((pos[0], pos[1]), (nbrPos[0] + offsetX, nbrPos[1] + offsetY), (nbrPos[0] - offsetX, nbrPos[1] - offsetY)) #canvas.drawPolygon(poly,edgeColor=color,edgeWidth=1,fillColor=color,closed=1) if not dash: self.canvas.addCanvasPolygon(poly, color=color) elif self.drawingOptions.wedgeDashedBonds and self.canvas.addCanvasDashedWedge: self.canvas.addCanvasDashedWedge(poly[0], poly[1], poly[2], color=color) else: self.canvas.addCanvasLine(pos, nbrPos, linewidth=width * 2, color=color, dashes=dash) def _drawBond(self, bond, atom, nbr, pos, nbrPos, conf, width=None, color=None, color2=None, labelSize1=None, labelSize2=None): if width is None: width = self.drawingOptions.bondLineWidth if color is None: color = self.drawingOptions.defaultColor p1_raw = copy.deepcopy(pos) p2_raw = copy.deepcopy(nbrPos) newpos = self._getBondAttachmentCoordinates(p1_raw, p2_raw, labelSize1) newnbrPos = self._getBondAttachmentCoordinates(p2_raw, p1_raw, labelSize2) bType = bond.GetBondType() if bType == Chem.BondType.SINGLE: bDir = bond.GetBondDir() if bDir in (Chem.BondDir.BEGINWEDGE, Chem.BondDir.BEGINDASH): # if the bond is "backwards", change the drawing direction: if bond.GetBeginAtom().GetChiralTag() in (Chem.ChiralType.CHI_TETRAHEDRAL_CW, Chem.ChiralType.CHI_TETRAHEDRAL_CCW): p1, p2 = newpos, newnbrPos wcolor = color else: p2, p1 = newpos, newnbrPos if color2 is not None: wcolor = color2 else: wcolor = self.drawingOptions.defaultColor if bDir == Chem.BondDir.BEGINWEDGE: self._drawWedgedBond(bond, p1, p2, color=wcolor, width=width) elif bDir == Chem.BondDir.BEGINDASH: self._drawWedgedBond(bond, p1, p2, color=wcolor, width=width, dash=self.drawingOptions.dash) else: self.canvas.addCanvasLine(newpos, newnbrPos, linewidth=width, color=color, color2=color2) elif bType == Chem.BondType.DOUBLE: crossBond = (self.drawingOptions.showUnknownDoubleBonds and \ bond.GetStereo() == Chem.BondStereo.STEREOANY) if not crossBond and \ ( bond.IsInRing() or (atom.GetDegree()!=1 and bond.GetOtherAtom(atom).GetDegree()!=1) ): self.canvas.addCanvasLine(newpos, newnbrPos, linewidth=width, color=color, color2=color2) fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf) self.canvas.addCanvasLine(fp1, fp2, linewidth=width, color=color, color2=color2) else: fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf, dir=.5, lenFrac=1.0) fp3, fp4 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf, dir=-.5, lenFrac=1.0) if crossBond: fp2, fp4 = fp4, fp2 self.canvas.addCanvasLine(fp1, fp2, linewidth=width, color=color, color2=color2) self.canvas.addCanvasLine(fp3, fp4, linewidth=width, color=color, color2=color2) elif bType == Chem.BondType.AROMATIC: self.canvas.addCanvasLine(newpos, newnbrPos, linewidth=width, color=color, color2=color2) fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf) self.canvas.addCanvasLine(fp1, fp2, linewidth=width, color=color, color2=color2, dash=self.drawingOptions.dash) elif bType == Chem.BondType.TRIPLE: self.canvas.addCanvasLine(newpos, newnbrPos, linewidth=width, color=color, color2=color2) fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf) self.canvas.addCanvasLine(fp1, fp2, linewidth=width, color=color, color2=color2) fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf, dir=-1) self.canvas.addCanvasLine(fp1, fp2, linewidth=width, color=color, color2=color2) else: self.canvas.addCanvasLine(newpos, newnbrPos, linewidth=width, color=color, color2=color2, dash=(1, 2)) def scaleAndCenter(self, mol, conf, coordCenter=False, canvasSize=None, ignoreHs=False): if canvasSize is None: canvasSize = self.canvasSize xAccum = 0 yAccum = 0 minX = 1e8 minY = 1e8 maxX = -1e8 maxY = -1e8 nAts = mol.GetNumAtoms() for i in range(nAts): if ignoreHs and mol.GetAtomWithIdx(i).GetAtomicNum() == 1: continue pos = conf.GetAtomPosition(i) * self.drawingOptions.coordScale xAccum += pos[0] yAccum += pos[1] minX = min(minX, pos[0]) minY = min(minY, pos[1]) maxX = max(maxX, pos[0]) maxY = max(maxY, pos[1]) dx = abs(maxX - minX) dy = abs(maxY - minY) xSize = dx * self.currDotsPerAngstrom ySize = dy * self.currDotsPerAngstrom if coordCenter: molTrans = -xAccum / nAts, -yAccum / nAts else: molTrans = -(minX + (maxX - minX) / 2), -(minY + (maxY - minY) / 2) self.molTrans = molTrans if xSize >= .95 * canvasSize[0]: scale = .9 * canvasSize[0] / xSize xSize *= scale ySize *= scale self.currDotsPerAngstrom *= scale self.currAtomLabelFontSize = max(self.currAtomLabelFontSize * scale, self.drawingOptions.atomLabelMinFontSize) if ySize >= .95 * canvasSize[1]: scale = .9 * canvasSize[1] / ySize xSize *= scale ySize *= scale self.currDotsPerAngstrom *= scale self.currAtomLabelFontSize = max(self.currAtomLabelFontSize * scale, self.drawingOptions.atomLabelMinFontSize) drawingTrans = canvasSize[0] / 2, canvasSize[1] / 2 self.drawingTrans = drawingTrans def _drawLabel(self, label, pos, baseOffset, font, color=None, **kwargs): if color is None: color = self.drawingOptions.defaultColor x1 = pos[0] y1 = pos[1] labelP = x1, y1 labelSize = self.canvas.addCanvasText(label, (x1, y1, baseOffset), font, color, **kwargs) return labelSize def AddMol(self, mol, centerIt=True, molTrans=None, drawingTrans=None, highlightAtoms=[], confId=-1, flagCloseContactsDist=2, highlightMap=None, ignoreHs=False, highlightBonds=[], **kwargs): """Set the molecule to be drawn. Parameters: hightlightAtoms -- list of atoms to highlight (default []) highlightMap -- dictionary of (atom, color) pairs (default None) Notes: - specifying centerIt will cause molTrans and drawingTrans to be ignored """ conf = mol.GetConformer(confId) if 'coordScale' in kwargs: self.drawingOptions.coordScale = kwargs['coordScale'] self.currDotsPerAngstrom = self.drawingOptions.dotsPerAngstrom self.currAtomLabelFontSize = self.drawingOptions.atomLabelFontSize if centerIt: self.scaleAndCenter(mol, conf, ignoreHs=ignoreHs) else: if molTrans is None: molTrans = (0, 0) self.molTrans = molTrans if drawingTrans is None: drawingTrans = (0, 0) self.drawingTrans = drawingTrans font = Font(face=self.drawingOptions.atomLabelFontFace, size=self.currAtomLabelFontSize) obds = None if not mol.HasProp('_drawingBondsWedged'): # this is going to modify the molecule, get ready to undo that obds = [x.GetBondDir() for x in mol.GetBonds()] Chem.WedgeMolBonds(mol, conf) includeAtomNumbers = kwargs.get('includeAtomNumbers', self.drawingOptions.includeAtomNumbers) self.atomPs[mol] = {} self.boundingBoxes[mol] = [0] * 4 self.activeMol = mol self.bondRings = mol.GetRingInfo().BondRings() labelSizes = {} for atom in mol.GetAtoms(): labelSizes[atom.GetIdx()] = None if ignoreHs and atom.GetAtomicNum() == 1: drawAtom = False else: drawAtom = True idx = atom.GetIdx() pos = self.atomPs[mol].get(idx, None) if pos is None: pos = self.transformPoint(conf.GetAtomPosition(idx) * self.drawingOptions.coordScale) self.atomPs[mol][idx] = pos if drawAtom: self.boundingBoxes[mol][0] = min(self.boundingBoxes[mol][0], pos[0]) self.boundingBoxes[mol][1] = min(self.boundingBoxes[mol][1], pos[1]) self.boundingBoxes[mol][2] = max(self.boundingBoxes[mol][2], pos[0]) self.boundingBoxes[mol][3] = max(self.boundingBoxes[mol][3], pos[1]) if not drawAtom: continue nbrSum = [0, 0] for bond in atom.GetBonds(): nbr = bond.GetOtherAtom(atom) if ignoreHs and nbr.GetAtomicNum() == 1: continue nbrIdx = nbr.GetIdx() if nbrIdx > idx: nbrPos = self.atomPs[mol].get(nbrIdx, None) if nbrPos is None: nbrPos = self.transformPoint( conf.GetAtomPosition(nbrIdx) * self.drawingOptions.coordScale) self.atomPs[mol][nbrIdx] = nbrPos self.boundingBoxes[mol][0] = min(self.boundingBoxes[mol][0], nbrPos[0]) self.boundingBoxes[mol][1] = min(self.boundingBoxes[mol][1], nbrPos[1]) self.boundingBoxes[mol][2] = max(self.boundingBoxes[mol][2], nbrPos[0]) self.boundingBoxes[mol][3] = max(self.boundingBoxes[mol][3], nbrPos[1]) else: nbrPos = self.atomPs[mol][nbrIdx] nbrSum[0] += nbrPos[0] - pos[0] nbrSum[1] += nbrPos[1] - pos[1] iso = atom.GetIsotope() labelIt= not self.drawingOptions.noCarbonSymbols or \ atom.GetAtomicNum()!=6 or \ atom.GetFormalCharge()!=0 or \ atom.GetNumRadicalElectrons() or \ includeAtomNumbers or \ iso or \ atom.HasProp('molAtomMapNumber') or \ atom.GetDegree()==0 orient = '' if labelIt: baseOffset = 0 if includeAtomNumbers: symbol = str(atom.GetIdx()) symbolLength = len(symbol) else: base = atom.GetSymbol() if (base == 'H' and (iso == 2 or iso == 3) and self.drawingOptions.atomLabelDeuteriumTritium): if (iso == 2): base = 'D' else: base = 'T' iso = 0 symbolLength = len(base) if not atom.HasQuery(): nHs = atom.GetTotalNumHs() else: nHs = 0 if nHs > 0: if nHs > 1: hs = 'H<sub>%d</sub>' % nHs symbolLength += 1 + len(str(nHs)) else: hs = 'H' symbolLength += 1 else: hs = '' chg = atom.GetFormalCharge() if chg != 0: if chg == 1: chg = '+' elif chg == -1: chg = '-' elif chg > 1: chg = '+%d' % chg elif chg < -1: chg = '-%d' % chg symbolLength += len(chg) else: chg = '' if chg: chg = '<sup>%s</sup>' % chg if atom.GetNumRadicalElectrons(): rad = self.drawingOptions.radicalSymbol * atom.GetNumRadicalElectrons() rad = '<sup>%s</sup>' % rad symbolLength += atom.GetNumRadicalElectrons() else: rad = '' isotope = '' isotopeLength = 0 if iso: isotope = '<sup>%d</sup>' % atom.GetIsotope() isotopeLength = len(str(atom.GetIsotope())) symbolLength += isotopeLength mapNum = '' mapNumLength = 0 if atom.HasProp('molAtomMapNumber'): mapNum = ':' + atom.GetProp('molAtomMapNumber') mapNumLength = 1 + len(str(atom.GetProp('molAtomMapNumber'))) symbolLength += mapNumLength deg = atom.GetDegree() # This should be done in a better way in the future: # 'baseOffset' should be determined by getting the size of 'isotope' and the size of 'base', or the size of 'mapNum' and the size of 'base' # (depending on 'deg' and 'nbrSum[0]') in order to determine the exact position of the base if deg == 0: if periodicTable.GetElementSymbol(atom.GetAtomicNum()) in ('O', 'S', 'Se', 'Te', 'F', 'Cl', 'Br', 'I', 'At'): symbol = '%s%s%s%s%s%s' % (hs, isotope, base, chg, rad, mapNum) else: symbol = '%s%s%s%s%s%s' % (isotope, base, hs, chg, rad, mapNum) elif deg > 1 or nbrSum[0] < 1: symbol = '%s%s%s%s%s%s' % (isotope, base, hs, chg, rad, mapNum) baseOffset = 0.5 - (isotopeLength + len(base) / 2.) / symbolLength else: symbol = '%s%s%s%s%s%s' % (rad, chg, hs, isotope, base, mapNum) baseOffset = -0.5 + (mapNumLength + len(base) / 2.) / symbolLength if deg == 1: if abs(nbrSum[1]) > 1: islope = nbrSum[0] / abs(nbrSum[1]) else: islope = nbrSum[0] if abs(islope) > .3: if islope > 0: orient = 'W' else: orient = 'E' elif abs(nbrSum[1]) > 10: if nbrSum[1] > 0: orient = 'N' else: orient = 'S' else: orient = 'C' if highlightMap and idx in highlightMap: color = highlightMap[idx] elif highlightAtoms and idx in highlightAtoms: color = self.drawingOptions.selectColor else: color = self.drawingOptions.elemDict.get(atom.GetAtomicNum(), (0, 0, 0)) labelSize = self._drawLabel(symbol, pos, baseOffset, font, color=color, orientation=orient) labelSizes[atom.GetIdx()] = [labelSize, orient] for bond in mol.GetBonds(): atom, idx = bond.GetBeginAtom(), bond.GetBeginAtomIdx() nbr, nbrIdx = bond.GetEndAtom(), bond.GetEndAtomIdx() pos = self.atomPs[mol].get(idx, None) nbrPos = self.atomPs[mol].get(nbrIdx, None) if highlightBonds and bond.GetIdx() in highlightBonds: width = 2.0 * self.drawingOptions.bondLineWidth color = self.drawingOptions.selectColor color2 = self.drawingOptions.selectColor elif highlightAtoms and idx in highlightAtoms and nbrIdx in highlightAtoms: width = 2.0 * self.drawingOptions.bondLineWidth color = self.drawingOptions.selectColor color2 = self.drawingOptions.selectColor elif highlightMap is not None and idx in highlightMap and nbrIdx in highlightMap: width = 2.0 * self.drawingOptions.bondLineWidth color = highlightMap[idx] color2 = highlightMap[nbrIdx] else: width = self.drawingOptions.bondLineWidth if self.drawingOptions.colorBonds: color = self.drawingOptions.elemDict.get(atom.GetAtomicNum(), (0, 0, 0)) color2 = self.drawingOptions.elemDict.get(nbr.GetAtomicNum(), (0, 0, 0)) else: color = self.drawingOptions.defaultColor color2 = color self._drawBond(bond, atom, nbr, pos, nbrPos, conf, color=color, width=width, color2=color2, labelSize1=labelSizes[idx], labelSize2=labelSizes[nbrIdx]) # if we modified the bond wedging state, undo those changes now if obds: for i, d in enumerate(obds): mol.GetBondWithIdx(i).SetBondDir(d) if flagCloseContactsDist > 0: tol = flagCloseContactsDist * flagCloseContactsDist for i, atomi in enumerate(mol.GetAtoms()): pi = numpy.array(self.atomPs[mol][i]) for j in range(i + 1, mol.GetNumAtoms()): pj = numpy.array(self.atomPs[mol][j]) d = pj - pi dist2 = d[0] * d[0] + d[1] * d[1] if dist2 <= tol: self.canvas.addCanvasPolygon( ((pi[0] - 2 * flagCloseContactsDist, pi[1] - 2 * flagCloseContactsDist), (pi[0] + 2 * flagCloseContactsDist, pi[1] - 2 * flagCloseContactsDist), ( pi[0] + 2 * flagCloseContactsDist, pi[1] + 2 * flagCloseContactsDist), (pi[0] - 2 * flagCloseContactsDist, pi[1] + 2 * flagCloseContactsDist)), color=(1., 0, 0), fill=False, stroke=True)
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Draw/MolDrawing.py", "copies": "1", "size": "23238", "license": "bsd-3-clause", "hash": 8287087215908858000, "line_mean": 37.5373134328, "line_max": 149, "alpha_frac": 0.5855925639, "autogenerated": false, "ratio": 3.235588972431078, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4321181536331078, "avg_score": null, "num_lines": null }
from rdkit import Chem from rdkit import RDConfig import numpy import math class Font(object): face='sans' size='12' weight='normal' name=None def __init__(self,face=None,size=None,name=None,weight=None): if face: self.face=face if size: self.size=size if name: self.name=name if weight: self.weight=weight class MolDrawing(object): dotsPerAngstrom = 30 useFraction=0.85 atomLabelFontFace = "sans" atomLabelFontSize = 12 atomLabelMinFontSize = 7 bondLineWidth = 1.2 dblBondOffset = .3 dblBondLengthFrac = .8 defaultColor = (1,0,0) selectColor = (1,0,0) colorBonds=True noCarbonSymbols=True includeAtomNumbers=False atomNumberOffset=0 radicalSymbol=u'\u2219' dash = (4,4) atomPs = None canvas = None canvasSize=None wedgeDashedBonds=True # used to adjust overall scaling for molecules that have been laid out with non-standard # bond lengths coordScale=1.0 elemDict={ 7:(0,0,1), 8:(1,0,0), 9:(.2,.8,.8), 15:(1,.5,0), 16:(.8,.8,0), 17:(0,.8,0), 35:(.5,.3,.1), 0:(.5,.5,.5), } def __init__(self,canvas=None): self.canvas = canvas if canvas: self.canvasSize=canvas.size self.atomPs = {} self.boundingBoxes = {} def transformPoint(self,pos): res = [0,0] res[0] = (pos[0] + self.molTrans[0])*self.currDotsPerAngstrom*self.useFraction + self.drawingTrans[0] res[1] = self.canvasSize[1]-((pos[1] + self.molTrans[1])*self.currDotsPerAngstrom*self.useFraction + \ self.drawingTrans[1]) return res def _getBondOffset(self,p1,p2): # get the vector between the points: dx = p2[0]-p1[0] dy = p2[1]-p1[1] # figure out the angle and the perpendicular: ang = math.atan2(dy,dx) perp = ang + math.pi/2. # here's the offset for the parallel bond: offsetX = math.cos(perp)*self.dblBondOffset*self.currDotsPerAngstrom offsetY = math.sin(perp)*self.dblBondOffset*self.currDotsPerAngstrom return perp,offsetX,offsetY def _getOffsetBondPts(self,p1,p2, offsetX,offsetY, lenFrac=None): if not lenFrac: lenFrac = self.dblBondLengthFrac dx = p2[0]-p1[0] dy = p2[1]-p1[1] # ---- # now figure out where to start and end it: # offset the start point: fracP1 = p1[0]+offsetX,p1[1]+offsetY # now move a portion of the way along the line to the neighbor: frac = (1.-lenFrac)/2 fracP1 = fracP1[0]+dx*frac,\ fracP1[1]+dy*frac fracP2 = fracP1[0]+dx*lenFrac,\ fracP1[1]+dy*lenFrac return fracP1,fracP2 def _offsetDblBond(self,p1,p2,bond,a1,a2,conf,dir=1, lenFrac=None): perp,offsetX,offsetY = self._getBondOffset(p1,p2) offsetX = offsetX*dir offsetY = offsetY*dir # if we're a ring bond, we may need to flip over to the other side: if bond.IsInRing(): bondIdx = bond.GetIdx() a1Idx = a1.GetIdx() a2Idx = a2.GetIdx() # find a ring bond from a1 to an atom other than a2: for otherBond in a1.GetBonds(): if otherBond.GetIdx()!=bondIdx and \ otherBond.IsInRing(): sharedRing=False for ring in self.bondRings: if bondIdx in ring and otherBond.GetIdx() in ring: sharedRing=True break if not sharedRing: continue a3 = otherBond.GetOtherAtom(a1) if a3.GetIdx() != a2Idx: p3 = self.transformPoint(conf.GetAtomPosition(a3.GetIdx())*self.coordScale) dx2 = p3[0] - p1[0] dy2 = p3[1] - p1[1] dotP = dx2*offsetX + dy2*offsetY if dotP < 0: perp += math.pi offsetX = math.cos(perp)*self.dblBondOffset*self.currDotsPerAngstrom offsetY = math.sin(perp)*self.dblBondOffset*self.currDotsPerAngstrom fracP1,fracP2 = self._getOffsetBondPts(p1,p2, offsetX,offsetY, lenFrac=lenFrac) return fracP1,fracP2 def _drawWedgedBond(self,bond,pos,nbrPos, width=bondLineWidth,color=defaultColor, dash=None): perp,offsetX,offsetY = self._getBondOffset(pos,nbrPos) offsetX *=.75 offsetY *=.75 poly = ((pos[0],pos[1]), (nbrPos[0]+offsetX,nbrPos[1]+offsetY), (nbrPos[0]-offsetX,nbrPos[1]-offsetY)) #canvas.drawPolygon(poly,edgeColor=color,edgeWidth=1,fillColor=color,closed=1) if not dash: self.canvas.addCanvasPolygon(poly,color=color) elif self.wedgeDashedBonds and self.canvas.addCanvasDashedWedge: self.canvas.addCanvasDashedWedge(poly[0],poly[1],poly[2],color=color) else: self.canvas.addCanvasLine(pos,nbrPos,linewidth=width*2,color=color, dashes=dash) def _drawBond(self,bond,atom,nbr,pos,nbrPos,conf, width=bondLineWidth,color=defaultColor,color2=None): bType=bond.GetBondType() if bType == Chem.BondType.SINGLE: bDir = bond.GetBondDir() if bDir in (Chem.BondDir.BEGINWEDGE,Chem.BondDir.BEGINDASH): # if the bond is "backwards", change the drawing direction: if bond.GetBeginAtom().GetChiralTag() in (Chem.ChiralType.CHI_TETRAHEDRAL_CW, Chem.ChiralType.CHI_TETRAHEDRAL_CCW): p1,p2 = pos,nbrPos else: p2,p1 = pos,nbrPos if bDir==Chem.BondDir.BEGINWEDGE: self._drawWedgedBond(bond,p1,p2,color=color,width=width) elif bDir==Chem.BondDir.BEGINDASH: self._drawWedgedBond(bond,p1,p2,color=color,width=width, dash=self.dash) else: self.canvas.addCanvasLine(pos, nbrPos, linewidth=width, color=color, color2=color2) elif bType == Chem.BondType.DOUBLE: if bond.IsInRing() or (atom.GetDegree()!=1 and bond.GetOtherAtom(atom).GetDegree()!=1): self.canvas.addCanvasLine(pos,nbrPos,linewidth=width,color=color,color2=color2) fp1,fp2 = self._offsetDblBond(pos,nbrPos,bond,atom,nbr,conf) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2) else: fp1,fp2 = self._offsetDblBond(pos,nbrPos,bond,atom,nbr,conf,dir=.5, lenFrac=1.0) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2) fp1,fp2 = self._offsetDblBond(pos,nbrPos,bond,atom,nbr,conf,dir=-.5, lenFrac=1.0) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2) elif bType == Chem.BondType.AROMATIC: self.canvas.addCanvasLine(pos,nbrPos,linewidth=width,color=color,color2=color2) fp1,fp2 = self._offsetDblBond(pos,nbrPos,bond,atom,nbr,conf) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2, dash=self.dash) elif bType == Chem.BondType.TRIPLE: self.canvas.addCanvasLine(pos,nbrPos,linewidth=width,color=color,color2=color2) fp1,fp2 = self._offsetDblBond(pos,nbrPos,bond,atom,nbr,conf) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2) fp1,fp2 = self._offsetDblBond(pos,nbrPos,bond,atom,nbr,conf,dir=-1) self.canvas.addCanvasLine(fp1,fp2,linewidth=width,color=color,color2=color2) else: self.canvas.addCanvasLine(pos, nbrPos, linewidth=width, color=color, color2=color2, dash=(1,2)) def scaleAndCenter(self,mol,conf,coordCenter=False,canvasSize=None,ignoreHs=False): self.currDotsPerAngstrom=self.dotsPerAngstrom self.currAtomLabelFontSize=self.atomLabelFontSize if canvasSize is None: canvasSize=self.canvasSize xAccum = 0 yAccum = 0 minX = 1e8 minY = 1e8 maxX = -1e8 maxY = -1e8 nAts = mol.GetNumAtoms() for i in range(nAts): if ignoreHs and mol.GetAtomWithIdx(i).GetAtomicNum()==1: continue pos = conf.GetAtomPosition(i)*self.coordScale xAccum += pos[0] yAccum += pos[1] minX = min(minX,pos[0]) minY = min(minY,pos[1]) maxX = max(maxX,pos[0]) maxY = max(maxY,pos[1]) dx = abs(maxX-minX) dy = abs(maxY-minY) xSize = dx*self.currDotsPerAngstrom ySize = dy*self.currDotsPerAngstrom if coordCenter: molTrans = -xAccum/nAts,-yAccum/nAts else: molTrans = -(minX+(maxX-minX)/2),-(minY+(maxY-minY)/2) self.molTrans = molTrans if xSize>=.95*canvasSize[0]: scale = .9*canvasSize[0]/xSize xSize*=scale ySize*=scale self.currDotsPerAngstrom*=scale self.currAtomLabelFontSize = max(self.currAtomLabelFontSize*scale, self.atomLabelMinFontSize) if ySize>=.95*canvasSize[1]: scale = .9*canvasSize[1]/ySize xSize*=scale ySize*=scale self.currDotsPerAngstrom*=scale self.currAtomLabelFontSize = max(self.currAtomLabelFontSize*scale, self.atomLabelMinFontSize) drawingTrans = canvasSize[0]/2,canvasSize[1]/2 self.drawingTrans = drawingTrans def _drawLabel(self,label,pos,font,color=None,**kwargs): if color is None: color = self.defaultColor x1 = pos[0] y1 = pos[1] labelP = x1,y1 self.canvas.addCanvasText(label,(x1,y1),font,color,**kwargs) def AddMol(self,mol,centerIt=True,molTrans=None,drawingTrans=None, highlightAtoms=[],confId=-1,flagCloseContactsDist=2, highlightMap=None, ignoreHs=False,highlightBonds=[],**kwargs): """Set the molecule to be drawn. Parameters: hightlightAtoms -- list of atoms to highlight (default []) highlightMap -- dictionary of (atom, color) pairs (default None) Notes: - specifying centerIt will cause molTrans and drawingTrans to be ignored """ conf = mol.GetConformer(confId) if kwargs.has_key('coordScale'): self.coordScale=kwargs['coordScale'] if centerIt: self.scaleAndCenter(mol,conf,ignoreHs=ignoreHs) else: if molTrans is None: molTrans = (0,0) self.molTrans = molTrans if drawingTrans is None: drawingTrans = (0,0) self.drawingTrans = drawingTrans font = Font(face=self.atomLabelFontFace,size=self.currAtomLabelFontSize) if not mol.HasProp('_drawingBondsWedged'): Chem.WedgeMolBonds(mol,conf) includeAtomNumbers = kwargs.get('includeAtomNumbers',self.includeAtomNumbers) self.atomPs[mol] = {} self.boundingBoxes[mol] = [0]*4 self.activeMol = mol self.bondRings = mol.GetRingInfo().BondRings() for atom in mol.GetAtoms(): if ignoreHs and atom.GetAtomicNum()==1: drawAtom=False else: drawAtom=True idx = atom.GetIdx() pos = self.atomPs[mol].get(idx,None) if pos is None: pos = self.transformPoint(conf.GetAtomPosition(idx)*self.coordScale) self.atomPs[mol][idx] = pos if drawAtom: self.boundingBoxes[mol][0]=min(self.boundingBoxes[mol][0],pos[0]) self.boundingBoxes[mol][1]=min(self.boundingBoxes[mol][1],pos[1]) self.boundingBoxes[mol][2]=max(self.boundingBoxes[mol][2],pos[0]) self.boundingBoxes[mol][3]=max(self.boundingBoxes[mol][3],pos[1]) if not drawAtom: continue nbrSum = [0,0] for bond in atom.GetBonds(): nbr = bond.GetOtherAtom(atom) if ignoreHs and nbr.GetAtomicNum()==1: continue nbrIdx = nbr.GetIdx() if nbrIdx > idx: nbrPos = self.atomPs[mol].get(nbrIdx,None) if nbrPos is None: nbrPos = self.transformPoint(conf.GetAtomPosition(nbrIdx)*self.coordScale) self.atomPs[mol][nbrIdx] = nbrPos self.boundingBoxes[mol][0]=min(self.boundingBoxes[mol][0],nbrPos[0]) self.boundingBoxes[mol][1]=min(self.boundingBoxes[mol][1],nbrPos[1]) self.boundingBoxes[mol][2]=max(self.boundingBoxes[mol][2],nbrPos[0]) self.boundingBoxes[mol][3]=max(self.boundingBoxes[mol][3],nbrPos[1]) if highlightBonds and bond.GetIdx() in highlightBonds: width=2.0*self.bondLineWidth color = self.selectColor color2 = self.selectColor elif highlightAtoms and idx in highlightAtoms and nbrIdx in highlightAtoms: width=2.0*self.bondLineWidth color = self.selectColor color2 = self.selectColor elif highlightMap is not None and idx in highlightMap and nbrIdx in highlightMap: width=2.0*self.bondLineWidth color = highlightMap[idx] color2 = highlightMap[nbrIdx] else: width=self.bondLineWidth if self.colorBonds: color = self.elemDict.get(atom.GetAtomicNum(),(0,0,0)) color2 = self.elemDict.get(nbr.GetAtomicNum(),(0,0,0)) else: color = self.defaultColor color2= color # make sure we draw from the beginning to the end # (this was Issue400) if idx==bond.GetBeginAtomIdx(): self._drawBond(bond,atom,nbr,pos,nbrPos,conf, color=color,width=width,color2=color2) else: self._drawBond(bond,nbr,atom,nbrPos,pos,conf, color=color2,width=width,color2=color) else: nbrPos = self.atomPs[mol][nbrIdx] nbrSum[0] += nbrPos[0]-pos[0] nbrSum[1] += nbrPos[1]-pos[1] iso = atom.GetIsotope() labelIt= not self.noCarbonSymbols or \ atom.GetAtomicNum()!=6 or \ atom.GetFormalCharge()!=0 or \ atom.GetNumRadicalElectrons() or \ includeAtomNumbers or \ iso or \ atom.HasProp('molAtomMapNumber') or \ atom.GetDegree()==0 orient='' if labelIt: if includeAtomNumbers: symbol = str(atom.GetIdx()) else: base = atom.GetSymbol() nHs = atom.GetTotalNumHs() if nHs>0: if nHs>1: hs='H<sub>%d</sub>'%nHs else: hs ='H' else: hs = '' chg = atom.GetFormalCharge() if chg!=0: if chg==1: chg = '+' elif chg==-1: chg = '-' elif chg>1: chg = '+%d'%chg elif chg<-1: chg = '-%d'%chg else: chg = '' if chg: chg = '<sup>%s</sup>'%chg if atom.GetNumRadicalElectrons(): rad = self.radicalSymbol*atom.GetNumRadicalElectrons() rad = '<sup>%s</sup>'%rad else: rad = '' isotope='' if iso: isotope='<sup>%d</sup>'%atom.GetIsotope() mapNum='' if atom.HasProp('molAtomMapNumber'): mapNum=':'+atom.GetProp('molAtomMapNumber') deg = atom.GetDegree() if deg>1 or nbrSum[0]<1: symbol = '%s%s%s%s%s%s'%(isotope,base,mapNum,hs,chg,rad) else: symbol = '%s%s%s%s%s%s'%(rad,chg,hs,isotope,base,mapNum) if deg==1: if abs(nbrSum[1])>1: islope=nbrSum[0]/abs(nbrSum[1]) else: islope=nbrSum[0] if abs(islope)>.3: if islope>0: orient='W' else: orient='E' elif abs(nbrSum[1])>10: if nbrSum[1]>0: orient='N' else : orient='S' else: orient = 'C' if highlightMap and idx in highlightMap: color = highlightMap[idx] elif highlightAtoms and idx in highlightAtoms: color = self.selectColor else: color = self.elemDict.get(atom.GetAtomicNum(),(0,0,0)) self._drawLabel(symbol, pos, font, color=color,orientation=orient) if flagCloseContactsDist>0: tol = flagCloseContactsDist*flagCloseContactsDist for i,atomi in enumerate(mol.GetAtoms()): pi = numpy.array(self.atomPs[mol][i]) for j in range(i+1,mol.GetNumAtoms()): pj = numpy.array(self.atomPs[mol][j]) d = pj-pi dist2 = d[0]*d[0]+d[1]*d[1] if dist2<=tol: self.canvas.addCanvasPolygon(((pi[0]-2*flagCloseContactsDist, pi[1]-2*flagCloseContactsDist), (pi[0]+2*flagCloseContactsDist, pi[1]-2*flagCloseContactsDist), (pi[0]+2*flagCloseContactsDist, pi[1]+2*flagCloseContactsDist), (pi[0]-2*flagCloseContactsDist, pi[1]+2*flagCloseContactsDist)), color=(1.,0,0), fill=False,stroke=True)
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Draw/MolDrawing.py", "copies": "1", "size": "17475", "license": "bsd-3-clause", "hash": 2140961963106832400, "line_mean": 34.736196319, "line_max": 106, "alpha_frac": 0.5835193133, "autogenerated": false, "ratio": 3.2421150278293136, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43256343411293136, "avg_score": null, "num_lines": null }
from rdkit import Chem import numpy import math import copy from rdkit.six import cmp import functools periodicTable = Chem.GetPeriodicTable() class Font(object): def __init__(self, face=None, size=None, name=None, weight=None): self.face = face or 'sans' self.size = size or '12' self.weight = weight or 'normal' self.name = name class DrawingOptions(object): dotsPerAngstrom = 30 useFraction = 0.85 atomLabelFontFace = "sans" atomLabelFontSize = 12 atomLabelMinFontSize = 7 atomLabelDeuteriumTritium = False bondLineWidth = 1.2 dblBondOffset = .25 dblBondLengthFrac = .8 defaultColor = (1, 0, 0) selectColor = (1, 0, 0) bgColor = (1, 1, 1) colorBonds = True noCarbonSymbols = True includeAtomNumbers = False atomNumberOffset = 0 radicalSymbol = u'\u2219' dash = (4, 4) wedgeDashedBonds = True showUnknownDoubleBonds = True # used to adjust overall scaling for molecules that have been laid out with non-standard # bond lengths coordScale = 1.0 elemDict = { 1: (0.55, 0.55, 0.55), 7: (0, 0, 1), 8: (1, 0, 0), 9: (.2, .8, .8), 15: (1, .5, 0), 16: (.8, .8, 0), 17: (0, .8, 0), 35: (.5, .3, .1), 53: (.63, .12, .94), 0: (.5, .5, .5), } class MolDrawing(object): def __init__(self, canvas=None, drawingOptions=None): self.canvas = canvas self.canvasSize = None if canvas: self.canvasSize = canvas.size self.drawingOptions = drawingOptions or DrawingOptions() self.atomPs = {} self.boundingBoxes = {} if self.drawingOptions.bgColor is not None: self.canvas.addCanvasPolygon(((0, 0), (canvas.size[0], 0), (canvas.size[0], canvas.size[1]), (0, canvas.size[1])), color=self.drawingOptions.bgColor, fill=True, stroke=False) def transformPoint(self, pos): res = [0, 0] res[0] = (pos[0] + self.molTrans[0] ) * self.currDotsPerAngstrom * self.drawingOptions.useFraction + self.drawingTrans[0] res[1] = self.canvasSize[1] - ((pos[1] + self.molTrans[1]) * self.currDotsPerAngstrom * self.drawingOptions.useFraction + self.drawingTrans[1]) return res def _getBondOffset(self, p1, p2): # get the vector between the points: dx = p2[0] - p1[0] dy = p2[1] - p1[1] # figure out the angle and the perpendicular: ang = math.atan2(dy, dx) perp = ang + math.pi / 2. # here's the offset for the parallel bond: offsetX = math.cos(perp) * self.drawingOptions.dblBondOffset * self.currDotsPerAngstrom offsetY = math.sin(perp) * self.drawingOptions.dblBondOffset * self.currDotsPerAngstrom return perp, offsetX, offsetY def _getOffsetBondPts(self, p1, p2, offsetX, offsetY, lenFrac=None): lenFrac = lenFrac or self.drawingOptions.dblBondLengthFrac dx = p2[0] - p1[0] dy = p2[1] - p1[1] # ---- # now figure out where to start and end it: # offset the start point: fracP1 = p1[0] + offsetX, p1[1] + offsetY # now move a portion of the way along the line to the neighbor: frac = (1. - lenFrac) / 2 fracP1 = fracP1[0] + dx * frac, fracP1[1] + dy * frac fracP2 = fracP1[0] + dx * lenFrac, fracP1[1] + dy * lenFrac return fracP1, fracP2 def _offsetDblBond(self, p1, p2, bond, a1, a2, conf, direction=1, lenFrac=None): perp, offsetX, offsetY = self._getBondOffset(p1, p2) offsetX = offsetX * direction offsetY = offsetY * direction # if we're a ring bond, we may need to flip over to the other side: if bond.IsInRing(): bondIdx = bond.GetIdx() a2Idx = a2.GetIdx() # find a ring bond from a1 to an atom other than a2: for otherBond in a1.GetBonds(): if otherBond.GetIdx() != bondIdx and otherBond.IsInRing(): sharedRing = False for ring in self.bondRings: if bondIdx in ring and otherBond.GetIdx() in ring: sharedRing = True break if not sharedRing: continue a3 = otherBond.GetOtherAtom(a1) if a3.GetIdx() != a2Idx: p3 = self.transformPoint( conf.GetAtomPosition(a3.GetIdx()) * self.drawingOptions.coordScale) dx2 = p3[0] - p1[0] dy2 = p3[1] - p1[1] dotP = dx2 * offsetX + dy2 * offsetY if dotP < 0: perp += math.pi offsetX = math.cos( perp) * self.drawingOptions.dblBondOffset * self.currDotsPerAngstrom offsetY = math.sin( perp) * self.drawingOptions.dblBondOffset * self.currDotsPerAngstrom fracP1, fracP2 = self._getOffsetBondPts(p1, p2, offsetX, offsetY, lenFrac=lenFrac) return fracP1, fracP2 def _getBondAttachmentCoordinates(self, p1, p2, labelSize): newpos = [None, None] if labelSize is not None: labelSizeOffset = [labelSize[0][0] / 2 + (cmp(p2[0], p1[0]) * labelSize[0][2]), labelSize[0][1] / 2] if p1[1] == p2[1]: newpos[0] = p1[0] + cmp(p2[0], p1[0]) * labelSizeOffset[0] else: if abs(labelSizeOffset[1] * (p2[0] - p1[0]) / (p2[1] - p1[1])) < labelSizeOffset[0]: newpos[0] = p1[0] + cmp(p2[0], p1[0]) * abs(labelSizeOffset[1] * (p2[0] - p1[0]) / (p2[1] - p1[1])) else: newpos[0] = p1[0] + cmp(p2[0], p1[0]) * labelSizeOffset[0] if p1[0] == p2[0]: newpos[1] = p1[1] + cmp(p2[1], p1[1]) * labelSizeOffset[1] else: if abs(labelSizeOffset[0] * (p1[1] - p2[1]) / (p2[0] - p1[0])) < labelSizeOffset[1]: newpos[1] = p1[1] + cmp(p2[1], p1[1]) * abs(labelSizeOffset[0] * (p1[1] - p2[1]) / (p2[0] - p1[0])) else: newpos[1] = p1[1] + cmp(p2[1], p1[1]) * labelSizeOffset[1] else: newpos = copy.deepcopy(p1) return newpos def _drawWedgedBond(self, bond, pos, nbrPos, width=None, color=None, dash=None): width = width or self.drawingOptions.bondLineWidth color = color or self.drawingOptions.defaultColor _, offsetX, offsetY = self._getBondOffset(pos, nbrPos) offsetX *= .75 offsetY *= .75 poly = ((pos[0], pos[1]), (nbrPos[0] + offsetX, nbrPos[1] + offsetY), (nbrPos[0] - offsetX, nbrPos[1] - offsetY)) # canvas.drawPolygon(poly,edgeColor=color,edgeWidth=1,fillColor=color,closed=1) if not dash: self.canvas.addCanvasPolygon(poly, color=color) elif self.drawingOptions.wedgeDashedBonds and self.canvas.addCanvasDashedWedge: self.canvas.addCanvasDashedWedge(poly[0], poly[1], poly[2], color=color) else: self.canvas.addCanvasLine(pos, nbrPos, linewidth=width * 2, color=color, dashes=dash) def _drawBond(self, bond, atom, nbr, pos, nbrPos, conf, width=None, color=None, color2=None, labelSize1=None, labelSize2=None): width = width or self.drawingOptions.bondLineWidth color = color or self.drawingOptions.defaultColor color2 = color2 or self.drawingOptions.defaultColor p1_raw = copy.deepcopy(pos) p2_raw = copy.deepcopy(nbrPos) newpos = self._getBondAttachmentCoordinates(p1_raw, p2_raw, labelSize1) newnbrPos = self._getBondAttachmentCoordinates(p2_raw, p1_raw, labelSize2) addDefaultLine = functools.partial(self.canvas.addCanvasLine, linewidth=width, color=color, color2=color2) bType = bond.GetBondType() if bType == Chem.BondType.SINGLE: bDir = bond.GetBondDir() if bDir in (Chem.BondDir.BEGINWEDGE, Chem.BondDir.BEGINDASH): # if the bond is "backwards", change the drawing direction: if bond.GetBeginAtom().GetChiralTag() in (Chem.ChiralType.CHI_TETRAHEDRAL_CW, Chem.ChiralType.CHI_TETRAHEDRAL_CCW): p1, p2 = newpos, newnbrPos wcolor = color else: p2, p1 = newpos, newnbrPos wcolor = color2 if bDir == Chem.BondDir.BEGINWEDGE: self._drawWedgedBond(bond, p1, p2, color=wcolor, width=width) elif bDir == Chem.BondDir.BEGINDASH: self._drawWedgedBond(bond, p1, p2, color=wcolor, width=width, dash=self.drawingOptions.dash) else: addDefaultLine(newpos, newnbrPos) elif bType == Chem.BondType.DOUBLE: crossBond = (self.drawingOptions.showUnknownDoubleBonds and bond.GetStereo() == Chem.BondStereo.STEREOANY) if (not crossBond and (bond.IsInRing() or (atom.GetDegree() != 1 and bond.GetOtherAtom(atom).GetDegree() != 1))): addDefaultLine(newpos, newnbrPos) fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf) addDefaultLine(fp1, fp2) else: fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf, direction=.5, lenFrac=1.0) fp3, fp4 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf, direction=-.5, lenFrac=1.0) if crossBond: fp2, fp4 = fp4, fp2 addDefaultLine(fp1, fp2) addDefaultLine(fp3, fp4) elif bType == Chem.BondType.AROMATIC: addDefaultLine(newpos, newnbrPos) fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf) addDefaultLine(fp1, fp2, dash=self.drawingOptions.dash) elif bType == Chem.BondType.TRIPLE: addDefaultLine(newpos, newnbrPos) fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf) addDefaultLine(fp1, fp2) fp1, fp2 = self._offsetDblBond(newpos, newnbrPos, bond, atom, nbr, conf, direction=-1) addDefaultLine(fp1, fp2) else: addDefaultLine(newpos, newnbrPos, dash=(1, 2)) def scaleAndCenter(self, mol, conf, coordCenter=False, canvasSize=None, ignoreHs=False): canvasSize = canvasSize or self.canvasSize xAccum = 0 yAccum = 0 minX = 1e8 minY = 1e8 maxX = -1e8 maxY = -1e8 nAts = mol.GetNumAtoms() for i in range(nAts): if ignoreHs and mol.GetAtomWithIdx(i).GetAtomicNum() == 1: continue pos = conf.GetAtomPosition(i) * self.drawingOptions.coordScale xAccum += pos[0] yAccum += pos[1] minX = min(minX, pos[0]) minY = min(minY, pos[1]) maxX = max(maxX, pos[0]) maxY = max(maxY, pos[1]) dx = abs(maxX - minX) dy = abs(maxY - minY) xSize = dx * self.currDotsPerAngstrom ySize = dy * self.currDotsPerAngstrom if coordCenter: molTrans = -xAccum / nAts, -yAccum / nAts else: molTrans = -(minX + (maxX - minX) / 2), -(minY + (maxY - minY) / 2) self.molTrans = molTrans if xSize >= .95 * canvasSize[0]: scale = .9 * canvasSize[0] / xSize xSize *= scale ySize *= scale self.currDotsPerAngstrom *= scale self.currAtomLabelFontSize = max(self.currAtomLabelFontSize * scale, self.drawingOptions.atomLabelMinFontSize) if ySize >= .95 * canvasSize[1]: scale = .9 * canvasSize[1] / ySize xSize *= scale ySize *= scale self.currDotsPerAngstrom *= scale self.currAtomLabelFontSize = max(self.currAtomLabelFontSize * scale, self.drawingOptions.atomLabelMinFontSize) drawingTrans = canvasSize[0] / 2, canvasSize[1] / 2 self.drawingTrans = drawingTrans def _drawLabel(self, label, pos, baseOffset, font, color=None, **kwargs): color = color or self.drawingOptions.defaultColor x1 = pos[0] y1 = pos[1] labelSize = self.canvas.addCanvasText(label, (x1, y1, baseOffset), font, color, **kwargs) return labelSize def AddMol(self, mol, centerIt=True, molTrans=None, drawingTrans=None, highlightAtoms=[], confId=-1, flagCloseContactsDist=2, highlightMap=None, ignoreHs=False, highlightBonds=[], **kwargs): """Set the molecule to be drawn. Parameters: hightlightAtoms -- list of atoms to highlight (default []) highlightMap -- dictionary of (atom, color) pairs (default None) Notes: - specifying centerIt will cause molTrans and drawingTrans to be ignored """ conf = mol.GetConformer(confId) if 'coordScale' in kwargs: self.drawingOptions.coordScale = kwargs['coordScale'] self.currDotsPerAngstrom = self.drawingOptions.dotsPerAngstrom self.currAtomLabelFontSize = self.drawingOptions.atomLabelFontSize if centerIt: self.scaleAndCenter(mol, conf, ignoreHs=ignoreHs) else: self.molTrans = molTrans or (0, 0) self.drawingTrans = drawingTrans or (0, 0) font = Font(face=self.drawingOptions.atomLabelFontFace, size=self.currAtomLabelFontSize) obds = None if not mol.HasProp('_drawingBondsWedged'): # this is going to modify the molecule, get ready to undo that obds = [x.GetBondDir() for x in mol.GetBonds()] Chem.WedgeMolBonds(mol, conf) includeAtomNumbers = kwargs.get('includeAtomNumbers', self.drawingOptions.includeAtomNumbers) self.atomPs[mol] = {} self.boundingBoxes[mol] = [0] * 4 self.activeMol = mol self.bondRings = mol.GetRingInfo().BondRings() labelSizes = {} for atom in mol.GetAtoms(): labelSizes[atom.GetIdx()] = None if ignoreHs and atom.GetAtomicNum() == 1: drawAtom = False else: drawAtom = True idx = atom.GetIdx() pos = self.atomPs[mol].get(idx, None) if pos is None: pos = self.transformPoint(conf.GetAtomPosition(idx) * self.drawingOptions.coordScale) self.atomPs[mol][idx] = pos if drawAtom: self.boundingBoxes[mol][0] = min(self.boundingBoxes[mol][0], pos[0]) self.boundingBoxes[mol][1] = min(self.boundingBoxes[mol][1], pos[1]) self.boundingBoxes[mol][2] = max(self.boundingBoxes[mol][2], pos[0]) self.boundingBoxes[mol][3] = max(self.boundingBoxes[mol][3], pos[1]) if not drawAtom: continue nbrSum = [0, 0] for bond in atom.GetBonds(): nbr = bond.GetOtherAtom(atom) if ignoreHs and nbr.GetAtomicNum() == 1: continue nbrIdx = nbr.GetIdx() if nbrIdx > idx: nbrPos = self.atomPs[mol].get(nbrIdx, None) if nbrPos is None: nbrPos = self.transformPoint( conf.GetAtomPosition(nbrIdx) * self.drawingOptions.coordScale) self.atomPs[mol][nbrIdx] = nbrPos self.boundingBoxes[mol][0] = min(self.boundingBoxes[mol][0], nbrPos[0]) self.boundingBoxes[mol][1] = min(self.boundingBoxes[mol][1], nbrPos[1]) self.boundingBoxes[mol][2] = max(self.boundingBoxes[mol][2], nbrPos[0]) self.boundingBoxes[mol][3] = max(self.boundingBoxes[mol][3], nbrPos[1]) else: nbrPos = self.atomPs[mol][nbrIdx] nbrSum[0] += nbrPos[0] - pos[0] nbrSum[1] += nbrPos[1] - pos[1] iso = atom.GetIsotope() labelIt = (not self.drawingOptions.noCarbonSymbols or iso or atom.GetAtomicNum() != 6 or atom.GetFormalCharge() != 0 or atom.GetNumRadicalElectrons() or includeAtomNumbers or atom.HasProp('molAtomMapNumber') or atom.GetDegree() == 0) orient = '' if labelIt: baseOffset = 0 if includeAtomNumbers: symbol = str(atom.GetIdx()) symbolLength = len(symbol) else: base = atom.GetSymbol() if (base == 'H' and (iso == 2 or iso == 3) and self.drawingOptions.atomLabelDeuteriumTritium): if iso == 2: base = 'D' else: base = 'T' iso = 0 symbolLength = len(base) if not atom.HasQuery(): nHs = atom.GetTotalNumHs() else: nHs = 0 if nHs > 0: if nHs > 1: hs = 'H<sub>%d</sub>' % nHs symbolLength += 1 + len(str(nHs)) else: hs = 'H' symbolLength += 1 else: hs = '' chg = atom.GetFormalCharge() if chg == 0: chg = '' elif chg == 1: chg = '+' elif chg == -1: chg = '-' else: chg = '%+d' % chg symbolLength += len(chg) if chg: chg = '<sup>%s</sup>' % chg if atom.GetNumRadicalElectrons(): rad = self.drawingOptions.radicalSymbol * atom.GetNumRadicalElectrons() rad = '<sup>%s</sup>' % rad symbolLength += atom.GetNumRadicalElectrons() else: rad = '' isotope = '' isotopeLength = 0 if iso: isotope = '<sup>%d</sup>' % atom.GetIsotope() isotopeLength = len(str(atom.GetIsotope())) symbolLength += isotopeLength mapNum = '' mapNumLength = 0 if atom.HasProp('molAtomMapNumber'): mapNum = ':' + atom.GetProp('molAtomMapNumber') mapNumLength = 1 + len(str(atom.GetProp('molAtomMapNumber'))) symbolLength += mapNumLength deg = atom.GetDegree() # This should be done in a better way in the future: # 'baseOffset' should be determined by getting the size of 'isotope' and # the size of 'base', or the size of 'mapNum' and the size of 'base' # (depending on 'deg' and 'nbrSum[0]') in order to determine the exact # position of the base if deg == 0: if periodicTable.GetElementSymbol(atom.GetAtomicNum()) in ('O', 'S', 'Se', 'Te', 'F', 'Cl', 'Br', 'I', 'At'): symbol = '%s%s%s%s%s%s' % (hs, isotope, base, chg, rad, mapNum) else: symbol = '%s%s%s%s%s%s' % (isotope, base, hs, chg, rad, mapNum) elif deg > 1 or nbrSum[0] < 1: symbol = '%s%s%s%s%s%s' % (isotope, base, hs, chg, rad, mapNum) baseOffset = 0.5 - (isotopeLength + len(base) / 2.) / symbolLength else: symbol = '%s%s%s%s%s%s' % (rad, chg, hs, isotope, base, mapNum) baseOffset = -0.5 + (mapNumLength + len(base) / 2.) / symbolLength if deg == 1: if abs(nbrSum[1]) > 1: islope = nbrSum[0] / abs(nbrSum[1]) else: islope = nbrSum[0] if abs(islope) > .3: if islope > 0: orient = 'W' else: orient = 'E' elif abs(nbrSum[1]) > 10: if nbrSum[1] > 0: orient = 'N' else: orient = 'S' else: orient = 'C' if highlightMap and idx in highlightMap: color = highlightMap[idx] elif highlightAtoms and idx in highlightAtoms: color = self.drawingOptions.selectColor else: color = self.drawingOptions.elemDict.get(atom.GetAtomicNum(), (0, 0, 0)) labelSize = self._drawLabel(symbol, pos, baseOffset, font, color=color, orientation=orient) labelSizes[atom.GetIdx()] = [labelSize, orient] for bond in mol.GetBonds(): atom, idx = bond.GetBeginAtom(), bond.GetBeginAtomIdx() nbr, nbrIdx = bond.GetEndAtom(), bond.GetEndAtomIdx() pos = self.atomPs[mol].get(idx, None) nbrPos = self.atomPs[mol].get(nbrIdx, None) if highlightBonds and bond.GetIdx() in highlightBonds: width = 2.0 * self.drawingOptions.bondLineWidth color = self.drawingOptions.selectColor color2 = self.drawingOptions.selectColor elif highlightAtoms and idx in highlightAtoms and nbrIdx in highlightAtoms: width = 2.0 * self.drawingOptions.bondLineWidth color = self.drawingOptions.selectColor color2 = self.drawingOptions.selectColor elif highlightMap is not None and idx in highlightMap and nbrIdx in highlightMap: width = 2.0 * self.drawingOptions.bondLineWidth color = highlightMap[idx] color2 = highlightMap[nbrIdx] else: width = self.drawingOptions.bondLineWidth if self.drawingOptions.colorBonds: color = self.drawingOptions.elemDict.get(atom.GetAtomicNum(), (0, 0, 0)) color2 = self.drawingOptions.elemDict.get(nbr.GetAtomicNum(), (0, 0, 0)) else: color = self.drawingOptions.defaultColor color2 = color self._drawBond(bond, atom, nbr, pos, nbrPos, conf, color=color, width=width, color2=color2, labelSize1=labelSizes[idx], labelSize2=labelSizes[nbrIdx]) # if we modified the bond wedging state, undo those changes now if obds: for i, d in enumerate(obds): mol.GetBondWithIdx(i).SetBondDir(d) if flagCloseContactsDist > 0: tol = flagCloseContactsDist * flagCloseContactsDist for i, _ in enumerate(mol.GetAtoms()): pi = numpy.array(self.atomPs[mol][i]) for j in range(i + 1, mol.GetNumAtoms()): pj = numpy.array(self.atomPs[mol][j]) d = pj - pi dist2 = d[0] * d[0] + d[1] * d[1] if dist2 <= tol: self.canvas.addCanvasPolygon( ((pi[0] - 2 * flagCloseContactsDist, pi[1] - 2 * flagCloseContactsDist), (pi[0] + 2 * flagCloseContactsDist, pi[1] - 2 * flagCloseContactsDist), (pi[0] + 2 * flagCloseContactsDist, pi[1] + 2 * flagCloseContactsDist), (pi[0] - 2 * flagCloseContactsDist, pi[1] + 2 * flagCloseContactsDist)), color=(1., 0, 0), fill=False, stroke=True)
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/Draw/MolDrawing.py", "copies": "4", "size": "22070", "license": "bsd-3-clause", "hash": 3209564507075559400, "line_mean": 38.2704626335, "line_max": 100, "alpha_frac": 0.5870865428, "autogenerated": false, "ratio": 3.2251936285255005, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.012664804834953858, "num_lines": 562 }
import cairo if not hasattr(cairo.ImageSurface,'get_data'): raise ImportError,'cairo version too old' import math import rdkit.RDConfig import os,re import array try: import pangocairo except ImportError: pangocairo=None try: import pango except ImportError: pango=None from canvasbase import CanvasBase import Image class Canvas(CanvasBase): def __init__(self, image=None, # PIL image size=None, ctx=None, imageType=None, # determines file type fileName=None, # if set determines output file name ): """ Canvas can be used in four modes: 1) using the supplied PIL image 2) using the supplied cairo context ctx 3) writing to a file fileName with image type imageType 4) creating a cairo surface and context within the constructor """ self.image=None self.imageType=imageType if image is not None: try: imgd = image.tostring("raw","BGRA") except SystemError: r,g,b,a = image.split() imgd = Image.merge("RGBA",(b,g,r,a)).tostring("raw","RGBA") a = array.array('B',imgd) stride=image.size[0]*4 surface = cairo.ImageSurface.create_for_data ( a, cairo.FORMAT_ARGB32, image.size[0], image.size[1], stride) ctx = cairo.Context(surface) size=image.size[0], image.size[1] self.image=image elif size is not None: if cairo.HAS_PDF_SURFACE and imageType == "pdf": surface = cairo.PDFSurface (fileName, size[0], size[1]) elif cairo.HAS_SVG_SURFACE and imageType == "svg": surface = cairo.SVGSurface (fileName, size[0], size[1]) elif cairo.HAS_PS_SURFACE and imageType == "ps": surface = cairo.PSSurface (fileName, size[0], size[1]) elif imageType == "png": surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, size[0], size[1]) else: raise ValueError, "Unrecognized file type. Valid choices are pdf, svg, ps, and png" ctx = cairo.Context(surface) ctx.set_source_rgb(1,1,1) ctx.paint() else: surface=ctx.get_target() try: size=surface.get_width(),surface.get_height() except AttributeError: size=None self.ctx=ctx self.size=size self.surface=surface self.fileName=fileName def flush(self): """temporary interface, must be splitted to different methods, """ if self.fileName and self.imageType=='png': self.surface.write_to_png(self.fileName) elif self.image is not None: # on linux at least it seems like the PIL images are BGRA, not RGBA: self.image.fromstring(self.surface.get_data(), "raw","BGRA",0,1) self.surface.finish() elif self.imageType == "png": buffer=self.surface.get_data() return buffer def _doLine(self, p1, p2, **kwargs): if kwargs.get('dash',(0,0)) == (0,0): self.ctx.move_to(p1[0],p1[1]) self.ctx.line_to(p2[0],p2[1]) else: dash = kwargs['dash'] pts = self._getLinePoints(p1,p2,dash) currDash = 0 dashOn = True while currDash<(len(pts)-1): if dashOn: p1 = pts[currDash] p2 = pts[currDash+1] self.ctx.move_to(p1[0],p1[1]) self.ctx.line_to(p2[0],p2[1]) currDash+=1 dashOn = not dashOn def addCanvasLine(self,p1,p2,color=(0,0,0),color2=None,**kwargs): self.ctx.set_line_width(kwargs.get('linewidth',1)) if color2 and color2!=color: mp = (p1[0]+p2[0])/2.,(p1[1]+p2[1])/2. self.ctx.set_source_rgb(*color) self._doLine(p1,mp,**kwargs) self.ctx.stroke() self.ctx.set_source_rgb(*color2) self._doLine(mp,p2,**kwargs) self.ctx.stroke() else: self.ctx.set_source_rgb(*color) self._doLine(p1,p2,**kwargs) self.ctx.stroke() def _addCanvasText1(self,text,pos,font,color=(0,0,0),**kwargs): if font.weight=='bold': weight=cairo.FONT_WEIGHT_BOLD else: weight=cairo.FONT_WEIGHT_NORMAL self.ctx.select_font_face(font.face, cairo.FONT_SLANT_NORMAL, weight) text = re.sub(r'\<.+?\>','',text) self.ctx.set_font_size(font.size) w,h=self.ctx.text_extents(text)[2:4] bw,bh=w*1.8,h*1.4 dPos = pos[0]-bw/2.,pos[1]-bh/2. bgColor=kwargs.get('bgColor',(1,1,1)) self.ctx.set_source_rgb(*bgColor) self.ctx.rectangle(dPos[0],dPos[1],bw,bh) self.ctx.fill() dPos = pos[0]-w/2.,pos[1]+h/2. self.ctx.set_source_rgb(*color) self.ctx.move_to(*dPos) self.ctx.show_text(text) def _addCanvasText2(self,text,pos,font,color=(0,0,0),**kwargs): if font.weight=='bold': weight=cairo.FONT_WEIGHT_BOLD else: weight=cairo.FONT_WEIGHT_NORMAL self.ctx.select_font_face(font.face, cairo.FONT_SLANT_NORMAL, weight) orientation=kwargs.get('orientation','E') cctx=pangocairo.CairoContext(self.ctx) lout = cctx.create_layout() lout.set_alignment(pango.ALIGN_LEFT) lout.set_markup(text) fnt = pango.FontDescription('%s %d'%(font.face,font.size)) lout.set_font_description(fnt) iext,lext=lout.get_pixel_extents() w=lext[2]-lext[0] h=lext[3]-lext[1] #bw,bh=w*1.8,h*1.4 if orientation=='W': dPos = pos[0]-w,pos[1]-h/2. elif orientation=='E': dPos = pos[0]-w/2,pos[1]-h/2. else: dPos = pos[0]-w/2,pos[1]-h/2. bgColor=kwargs.get('bgColor',(1,1,1)) self.ctx.set_source_rgb(*bgColor) self.ctx.rectangle(dPos[0],dPos[1],w,h) self.ctx.fill() self.ctx.move_to(dPos[0],dPos[1]) self.ctx.set_source_rgb(*color) cctx.update_layout(lout) cctx.show_layout(lout) def addCanvasText(self,text,pos,font,color=(0,0,0),**kwargs): if pango is not None and pangocairo is not None: self._addCanvasText2(text,pos,font,color,**kwargs) else: self._addCanvasText1(text,pos,font,color,**kwargs) def addCanvasPolygon(self,ps,color=(0,0,0),fill=True,stroke=False,**kwargs): if not fill and not stroke: return dps = [] self.ctx.set_source_rgb(*color) self.ctx.move_to(ps[0][0],ps[0][1]) for p in ps[1:]: self.ctx.line_to(p[0],p[1]) self.ctx.close_path() if stroke: if fill: self.ctx.stroke_preserve() else: self.ctx.stroke() if fill: self.ctx.fill() def addCanvasDashedWedge(self,p1,p2,p3,dash=(2,2),color=(0,0,0), color2=None,**kwargs): self.ctx.set_line_width(kwargs.get('linewidth',1)) self.ctx.set_source_rgb(*color) dash = (3,3) pts1 = self._getLinePoints(p1,p2,dash) pts2 = self._getLinePoints(p1,p3,dash) if len(pts2)<len(pts1): pts2,pts1=pts1,pts2 for i in range(len(pts1)): self.ctx.move_to(pts1[i][0],pts1[i][1]) self.ctx.line_to(pts2[i][0],pts2[i][1]) self.ctx.stroke() def addCircle(self,center,radius,color=(0,0,0),fill=True,stroke=False,alpha=1.0, **kwargs): if not fill and not stroke: return dps = [] #import pdb; pdb.set_trace(); self.ctx.set_source_rgba(color[0],color[1],color[2],alpha) self.ctx.arc(center[0],center[1],radius,0,2.*math.pi) self.ctx.close_path() if stroke: if fill: self.ctx.stroke_preserve() else: self.ctx.stroke() if fill: self.ctx.fill()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Draw/cairoCanvas.py", "copies": "1", "size": "7756", "license": "bsd-3-clause", "hash": -282730026080516100, "line_mean": 30.4008097166, "line_max": 91, "alpha_frac": 0.6036616813, "autogenerated": false, "ratio": 2.9796388782174414, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8900724331917345, "avg_score": 0.03651524552001951, "num_lines": 247 }
from aggdraw import Brush, Pen from aggdraw import Font import math from rdkit import RDConfig import os,re from aggdraw import Draw from canvasbase import CanvasBase faceMap={'sans':os.path.join(RDConfig.RDCodeDir,'Chem','Draw','FreeSans.ttf')} def convertColor(color): color = (int(color[0]*255),int(color[1]*255),int(color[2]*255)) return color class Canvas(CanvasBase): # fonts appear smaller in aggdraw than with cairo # fix that here: fontScale=1.2 def __init__(self, img=None, imageType=None, # determines file type fileName=None, # if set determines output file name size=None, ): if img is None: import Image if size is None: raise ValueError,'please provide either an image or a size' img = Image.new('RGBA',size,"white") self.image = img self.draw = Draw(img) self.draw.setantialias(True) if size is None: self.size = self.draw.size else: self.size = size if imageType and imageType not in ('png','jpg'): raise ValueError,'unsupported image type for agg canvas' self.drawType=imageType self.fileName=fileName def _doLine(self, p1, p2, pen, **kwargs): if kwargs.get('dash',(0,0)) == (0,0): self.draw.line((p1[0],p1[1],p2[0],p2[1]),pen) else: dash = kwargs['dash'] pts = self._getLinePoints(p1,p2,dash) currDash = 0 dashOn = True while currDash<(len(pts)-1): if dashOn: p1 = pts[currDash] p2 = pts[currDash+1] self.draw.line((p1[0],p1[1],p2[0],p2[1]),pen) currDash+=1 dashOn = not dashOn def addCanvasLine(self, p1, p2, color=(0,0,0), color2=None, **kwargs): if color2 and color2!=color: mp = (p1[0]+p2[0])/2.,(p1[1]+p2[1])/2. color = convertColor(color) self._doLine(p1,mp,Pen(color,kwargs.get('linewidth',1)),**kwargs) color2 = convertColor(color2) self._doLine(mp,p2,Pen(color2,kwargs.get('linewidth',1)),**kwargs) else: color = convertColor(color) self._doLine(p1,p2,Pen(color,kwargs.get('linewidth',1)),**kwargs) def addCanvasText(self,text,pos,font,color=(0,0,0),**kwargs): orientation=kwargs.get('orientation','E') color = convertColor(color) aggFont = Font(color,faceMap[font.face],size=font.size*self.fontScale) blocks = list(re.finditer(r'\<(.+?)\>(.+?)\</\1\>',text)) w,h = 0,0 supH=0 subH=0 if not len(blocks): w,h=self.draw.textsize(text,aggFont) bw,bh=w*1.1,h*1.1 dPos = pos[0]-bw/2.,pos[1]-bh/2. bgColor=kwargs.get('bgColor',(1,1,1)) bgColor = convertColor(bgColor) self.draw.rectangle((dPos[0],dPos[1],dPos[0]+bw,dPos[1]+bh), None,Brush(bgColor)) dPos = pos[0]-w/2.,pos[1]-h/2. self.draw.text(dPos,text,aggFont) else: dblocks=[] idx=0 for block in blocks: blockStart,blockEnd=block.span(0) if blockStart != idx: # untagged text: tblock = text[idx:blockStart] tw,th=self.draw.textsize(tblock,aggFont) w+=tw h = max(h,th) dblocks.append((tblock,'',tw,th)) fmt = block.groups()[0] tblock = block.groups()[1] if fmt in ('sub','sup'): lFont = Font(color,faceMap[font.face],size=0.8*font.size*self.fontScale) else: lFont = aggFont tw,th=self.draw.textsize(tblock,lFont) w+=tw if fmt == 'sub': subH = max(subH,th) elif fmt=='sup': supH = max(supH,th) else: h = max(h,th) dblocks.append((tblock,fmt,tw,th)) idx = blockEnd if idx!=len(text): # untagged text: tblock = text[idx:] tw,th=self.draw.textsize(tblock,aggFont) w+=tw h = max(h,th) dblocks.append((tblock,'',tw,th)) supH *= 0.25 subH *= 0.25 h += supH + subH bw,bh=w*1.1,h #dPos = pos[0]-bw/2.,pos[1]-bh/2. dPos = [pos[0]-w/2.,pos[1]-h/2.] if orientation=='W': dPos = [pos[0]-w,pos[1]-h/2.] elif orientation=='E': dPos = [pos[0],pos[1]-h/2.] else: dPos = [pos[0]-w/2,pos[1]-h/2.] bgColor=kwargs.get('bgColor',(1,1,1)) bgColor = convertColor(bgColor) self.draw.rectangle((dPos[0],dPos[1],dPos[0]+bw,dPos[1]+bh), None,Brush(bgColor)) if supH: dPos[1]+=supH for txt,fmt,tw,th in dblocks: tPos = dPos[:] if fmt=='sub': tPos[1]+=subH elif fmt=='sup': tPos[1]-=supH if fmt in ('sub','sup'): lFont = Font(color,faceMap[font.face],size=0.8*font.size*self.fontScale) else: lFont = aggFont self.draw.text(tPos,txt,lFont) dPos[0]+=tw def addCanvasPolygon(self,ps,color=(0,0,0),fill=True,stroke=False,**kwargs): if not fill and not stroke: return dps = [] for p in ps: dps.extend(p) color = convertColor(color) brush=None pen=None if fill: brush = Brush(color) if stroke: pen = Pen(color) self.draw.polygon(dps,pen,brush) def addCanvasDashedWedge(self,p1,p2,p3,dash=(2,2),color=(0,0,0), color2=None,**kwargs): pen = Pen(color,kwargs.get('linewidth',1)) dash = (3,3) pts1 = self._getLinePoints(p1,p2,dash) pts2 = self._getLinePoints(p1,p3,dash) if len(pts2)<len(pts1): pts2,pts1=pts1,pts2 for i in range(len(pts1)): self.draw.line((pts1[i][0],pts1[i][1],pts2[i][0],pts2[i][1]),pen) def flush(self): self.draw.flush() if self.fileName: self.image.save(self.fileName)
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Draw/aggCanvas.py", "copies": "1", "size": "5989", "license": "bsd-3-clause", "hash": 4157172736100534000, "line_mean": 29.4010152284, "line_max": 82, "alpha_frac": 0.5697111371, "autogenerated": false, "ratio": 2.9517003449975356, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40214114820975355, "avg_score": null, "num_lines": null }
from aggdraw import Brush, Pen #@UnresolvedImport #pylint: disable=F0401 from aggdraw import Font #@UnresolvedImport #pylint: disable=F0401 import math from rdkit import RDConfig import os, re from aggdraw import Draw #@UnresolvedImport #pylint: disable=F0401 from rdkit.Chem.Draw.canvasbase import CanvasBase faceMap = {'sans': os.path.join(RDConfig.RDCodeDir, 'Chem', 'Draw', 'FreeSans.ttf')} def convertColor(color): color = (int(color[0] * 255), int(color[1] * 255), int(color[2] * 255)) return color class Canvas(CanvasBase): # fonts appear smaller in aggdraw than with cairo # fix that here: fontScale = 1.2 def __init__(self, img=None, imageType=None, # determines file type fileName=None, # if set determines output file name size=None, ): if img is None: try: import Image except ImportError: from PIL import Image if size is None: raise ValueError('please provide either an image or a size') img = Image.new('RGBA', size, "white") self.image = img self.draw = Draw(img) self.draw.setantialias(True) if size is None: self.size = self.draw.size else: self.size = size if imageType and imageType not in ('png', 'jpg'): raise ValueError('unsupported image type for agg canvas') self.drawType = imageType self.fileName = fileName def _doLine(self, p1, p2, pen, **kwargs): if kwargs.get('dash', (0, 0)) == (0, 0): self.draw.line((p1[0], p1[1], p2[0], p2[1]), pen) else: dash = kwargs['dash'] pts = self._getLinePoints(p1, p2, dash) currDash = 0 dashOn = True while currDash < (len(pts) - 1): if dashOn: p1 = pts[currDash] p2 = pts[currDash + 1] self.draw.line((p1[0], p1[1], p2[0], p2[1]), pen) currDash += 1 dashOn = not dashOn def addCanvasLine(self, p1, p2, color=(0, 0, 0), color2=None, **kwargs): if color2 and color2 != color: mp = (p1[0] + p2[0]) / 2., (p1[1] + p2[1]) / 2. color = convertColor(color) self._doLine(p1, mp, Pen(color, kwargs.get('linewidth', 1)), **kwargs) color2 = convertColor(color2) self._doLine(mp, p2, Pen(color2, kwargs.get('linewidth', 1)), **kwargs) else: color = convertColor(color) self._doLine(p1, p2, Pen(color, kwargs.get('linewidth', 1)), **kwargs) def addCanvasText(self, text, pos, font, color=(0, 0, 0), **kwargs): orientation = kwargs.get('orientation', 'E') color = convertColor(color) aggFont = Font(color, faceMap[font.face], size=font.size * self.fontScale) blocks = list(re.finditer(r'\<(.+?)\>(.+?)\</\1\>', text)) w, h = 0, 0 supH = 0 subH = 0 if not len(blocks): w, h = self.draw.textsize(text, aggFont) tw, th = w, h offset = w * pos[2] dPos = pos[0] - w / 2. + offset, pos[1] - h / 2. self.draw.text(dPos, text, aggFont) else: dblocks = [] idx = 0 for block in blocks: blockStart, blockEnd = block.span(0) if blockStart != idx: # untagged text: tblock = text[idx:blockStart] tw, th = self.draw.textsize(tblock, aggFont) w += tw h = max(h, th) dblocks.append((tblock, '', tw, th)) fmt = block.groups()[0] tblock = block.groups()[1] if fmt in ('sub', 'sup'): lFont = Font(color, faceMap[font.face], size=0.8 * font.size * self.fontScale) else: lFont = aggFont tw, th = self.draw.textsize(tblock, lFont) w += tw if fmt == 'sub': subH = max(subH, th) elif fmt == 'sup': supH = max(supH, th) else: h = max(h, th) dblocks.append((tblock, fmt, tw, th)) idx = blockEnd if idx != len(text): # untagged text: tblock = text[idx:] tw, th = self.draw.textsize(tblock, aggFont) w += tw h = max(h, th) dblocks.append((tblock, '', tw, th)) supH *= 0.5 subH *= 0.5 h += supH + subH bw, bh = w + h * 0.4, w * 1.4 offset = w * pos[2] #dPos = pos[0]-bw/2.,pos[1]-bh/2. dPos = [pos[0] - w / 2. + offset, pos[1] - h / 2.] if orientation == 'W': dPos = [pos[0] - w + offset, pos[1] - h / 2.] elif orientation == 'E': dPos = [pos[0] + offset, pos[1] - h / 2.] else: dPos = [pos[0] - w / 2 + offset, pos[1] - h / 2.] if supH: dPos[1] += supH for txt, fmt, tw, th in dblocks: tPos = dPos[:] if fmt == 'sub': tPos[1] += subH elif fmt == 'sup': tPos[1] -= supH if fmt in ('sub', 'sup'): lFont = Font(color, faceMap[font.face], size=0.8 * font.size * self.fontScale) else: lFont = aggFont self.draw.text(tPos, txt, lFont) dPos[0] += tw return (tw + th * .4, th + th * .4, offset) def addCanvasPolygon(self, ps, color=(0, 0, 0), fill=True, stroke=False, **kwargs): if not fill and not stroke: return dps = [] for p in ps: dps.extend(p) color = convertColor(color) brush = None pen = None if fill: brush = Brush(color) if stroke: pen = Pen(color) self.draw.polygon(dps, pen, brush) def addCanvasDashedWedge(self, p1, p2, p3, dash=(2, 2), color=(0, 0, 0), color2=None, **kwargs): pen = Pen(color, kwargs.get('linewidth', 1)) dash = (3, 3) pts1 = self._getLinePoints(p1, p2, dash) pts2 = self._getLinePoints(p1, p3, dash) if len(pts2) < len(pts1): pts2, pts1 = pts1, pts2 for i in range(len(pts1)): self.draw.line((pts1[i][0], pts1[i][1], pts2[i][0], pts2[i][1]), pen) def flush(self): self.draw.flush() if self.fileName: self.image.save(self.fileName)
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Draw/aggCanvas.py", "copies": "1", "size": "6166", "license": "bsd-3-clause", "hash": 8242768089413088000, "line_mean": 30.2994923858, "line_max": 98, "alpha_frac": 0.5514109633, "autogenerated": false, "ratio": 3.053987122337791, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41053980856377903, "avg_score": null, "num_lines": null }
from matplotlib.lines import Line2D from matplotlib.patches import Polygon from matplotlib.axes import Axes from matplotlib.pyplot import figure #from matplotlib import textpath,font_manager import numpy from rdkit.Chem.Draw.canvasbase import CanvasBase class Canvas(CanvasBase): def __init__(self, size, name='', imageType='png'): self._name = name self.size=size dpi = max(size[0],size[1]) figsize=(int(float(size[0])/dpi),int(float(size[1])/dpi)) self._figure = figure(figsize=figsize) self._axes = self._figure.add_axes([0,0,2.5,2.5]) self._axes.set_xticklabels('') self._axes.set_yticklabels('') self._dpi = dpi def rescalePt(self,p1): return [float(p1[0])/self._dpi,float(self.size[1]-p1[1])/self._dpi] def addCanvasLine(self,p1,p2,color=(0,0,0),color2=None,**kwargs): canvas = self._axes p1 = self.rescalePt(p1) p2 = self.rescalePt(p2) if color2 and color2!=color: mp = (p1[0]+p2[0])/2.,(p1[1]+p2[1])/2. canvas.add_line(Line2D((p1[0],mp[0]),(p1[1],mp[1]), color=color,**kwargs)) canvas.add_line(Line2D((mp[0],p2[0]),(mp[1],p2[1]), color=color2,**kwargs)) else: canvas.add_line(Line2D((p1[0],p2[0]),(p1[1],p2[1]), color=color,**kwargs)) def addCanvasText(self,text,pos,font,color=(0,0,0),**kwargs): import re pos = self.rescalePt(pos) canvas = self._axes text = re.sub(r'<.*?>','',text) orientation=kwargs.get('orientation','E') halign='center' valign='center' if orientation=='E': halign='left' elif orientation=='W': halign='right' elif orientation=='S': valign='top' elif orientation=='N': valign='bottom' annot=canvas.annotate(text,(pos[0],pos[1]),color=color, verticalalignment=valign, horizontalalignment=halign, weight=font.weight, size=font.size*2.0, family=font.face, backgroundcolor='white') try: bb = annot.get_window_extent(renderer=self._figure.canvas.get_renderer()) w,h = bb.width,bb.height tw,th=canvas.transData.inverted().transform((w,h)) except AttributeError: tw,th = 0.1,0.1 # <- kludge #print annot.xytext,w,h,tw,th return (tw,th,0) def addCanvasPolygon(self,ps,color=(0,0,0),**kwargs): canvas = self._axes ps = [self.rescalePt(x) for x in ps] canvas.add_patch(Polygon(ps,linewidth=0,facecolor=color)) def addCanvasDashedWedge(self,p1,p2,p3,dash=(2,2),color=(0,0,0), color2=None,**kwargs): canvas = self._axes dash= (3,3) pts1 = self._getLinePoints(p1,p2,dash) pts2 = self._getLinePoints(p1,p3,dash) pts1 = [self.rescalePt(p) for p in pts1] pts2 = [self.rescalePt(p) for p in pts2] if len(pts2)<len(pts1): pts2,pts1=pts1,pts2 for i in range(len(pts1)): if color2 and color2!=color: mp = (pts1[i][0]+pts2[i][0])/2.,(pts1[i][1]+pts2[i][1])/2. canvas.add_line(Line2D((pts1[i][0],mp[0]),(pts1[i][1],mp[1]),color=color,**kwargs)) canvas.add_line(Line2D((mp[0],pts2[i][0]),(mp[1],pts2[i][1]),color=color2,**kwargs)) else: canvas.add_line(Line2D((pts1[i][0],pts2[i][0]),(pts1[i][1],pts2[i][1]),color=color,**kwargs))
{ "repo_name": "strets123/rdkit", "path": "rdkit/Chem/Draw/mplCanvas.py", "copies": "4", "size": "3703", "license": "bsd-3-clause", "hash": -2435710059567489000, "line_mean": 33.9339622642, "line_max": 101, "alpha_frac": 0.5873615987, "autogenerated": false, "ratio": 2.983883964544722, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.03734112839697097, "num_lines": 106 }
from matplotlib.lines import Line2D from matplotlib.patches import Polygon from matplotlib.axes import Axes from matplotlib.pyplot import figure import numpy from canvasbase import CanvasBase class Canvas(CanvasBase): def __init__(self, size, name='', imageType='png'): self._name = name self.size=size dpi = max(size[0],size[1]) figsize=(int(float(size[0])/dpi),int(float(size[1])/dpi)) self._figure = figure(figsize=figsize) self._axes = self._figure.add_axes([0,0,2.5,2.5]) self._axes.set_xticklabels('') self._axes.set_yticklabels('') self._dpi = dpi def rescalePt(self,p1): return [float(p1[0])/self._dpi,float(self.size[1]-p1[1])/self._dpi] def addCanvasLine(self,p1,p2,color=(0,0,0),color2=None,**kwargs): canvas = self._axes p1 = self.rescalePt(p1) p2 = self.rescalePt(p2) if color2 and color2!=color: mp = (p1[0]+p2[0])/2.,(p1[1]+p2[1])/2. canvas.add_line(Line2D((p1[0],mp[0]),(p1[1],mp[1]), color=color,**kwargs)) canvas.add_line(Line2D((mp[0],p2[0]),(mp[1],p2[1]), color=color2,**kwargs)) else: canvas.add_line(Line2D((p1[0],p2[0]),(p1[1],p2[1]), color=color,**kwargs)) def addCanvasText(self,text,pos,font,color=(0,0,0),**kwargs): import re pos = self.rescalePt(pos) canvas = self._axes text = re.sub(r'<.*?>','',text) canvas.annotate(text,(pos[0],pos[1]),color=color, verticalalignment='center', horizontalalignment='center', weight=font.weight, size=font.size*2.0, family=font.face, backgroundcolor="white") def addCanvasPolygon(self,ps,color=(0,0,0),**kwargs): canvas = self._axes ps = [self.rescalePt(x) for x in ps] canvas.add_patch(Polygon(ps,linewidth=0,facecolor=color))
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Draw/mplCanvas.py", "copies": "1", "size": "2199", "license": "bsd-3-clause", "hash": 3544188748159757300, "line_mean": 32.8307692308, "line_max": 71, "alpha_frac": 0.5952705775, "autogenerated": false, "ratio": 3.1103253182461104, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42055958957461104, "avg_score": null, "num_lines": null }
from rdkit.sping import pid import math,re from rdkit.sping.PIL.pidPIL import PILCanvas from canvasbase import CanvasBase faceMap={'sans':'helvetica', 'serif':'times'} def convertColor(color): color = pid.Color(color[0],color[1],color[2]) return color class Canvas(CanvasBase): def __init__(self, size, name, imageType='png'): if imageType=="pdf": from rdkit.sping.PDF.pidPDF import PDFCanvas as Canvas elif imageType=="ps": from rdkit.sping.PS.pidPS import PSCanvas as Canvas elif imageType=="svg": from rdkit.sping.SVG.pidSVG import SVGCanvas as Canvas elif imageType=="png": from rdkit.sping.PIL.pidPIL import PILCanvas as Canvas else: raise ValueError,'unrecognized format: %s'%imageType self.canvas = Canvas(size=size, name=name) if hasattr(self.canvas,'_image'): self._image = self.canvas._image else: self._image = None self.size = size def addCanvasLine(self, p1,p2,color=(0,0,0),color2=None,**kwargs): if color2 and color2!=color: mp = (p1[0]+p2[0])/2.,(p1[1]+p2[1])/2. color = convertColor(color) self.canvas.drawLine(p1[0],p1[1],mp[0],mp[1], color=color, width=int(kwargs.get('linewidth',1)), dash=kwargs.get('dash',None)) color2 = convertColor(color2) self.canvas.drawLine(mp[0],mp[1],p2[0],p2[1], color=color2, width=int(kwargs.get('linewidth',1)), dash=kwargs.get('dash',None)) else: color = convertColor(color) width=kwargs.get('linewidth',1) self.canvas.drawLine(p1[0],p1[1],p2[0],p2[1], color=color, width=int(width), dash=kwargs.get('dash',None)) def addCanvasText(self, text,pos,font,color=(0,0,0),**kwargs): text = re.sub(r'\<.+?\>','',text) font = pid.Font(face=faceMap[font.face],size=font.size) txtWidth,txtHeight=self.canvas.stringBox(text,font) labelP = pos[0]-txtWidth/2,pos[1]+txtHeight/2 xPad = kwargs.get('xPadding',0) yPad = kwargs.get('yPadding',0) x1 = pos[0]-txtWidth/2 - xPad y1 = pos[1]+txtHeight/2 + yPad x2 = pos[0]+txtWidth/2 + xPad y2 = pos[1]-txtHeight/2 - yPad bgColor=kwargs.get('bgColor',(1,1,1)) bgColor = convertColor(bgColor) self.canvas.drawRect(x1,y1,x2,y2, edgeColor=pid.transparent, edgeWidth=0,fillColor=bgColor) color = convertColor(color) self.canvas.drawString(text,labelP[0],labelP[1],font,color=color) def addCanvasPolygon(self, ps,color=(0,0,0),fill=True,stroke=False,**kwargs): if not fill and not stroke: return edgeWidth=kwargs.get('lineWidth',0) edgeColor=pid.transparent color = convertColor(color) if not stroke: edgeWidth=0 edgeColor=pid.transparent else: edgeWidth=kwargs.get('lineWidth',1) edgeColor=color if not fill: fillColor = pid.transparent else: fillColor = color self.canvas.drawPolygon(ps,edgeColor=edgeColor,edgeWidth=int(edgeWidth),fillColor=fillColor,closed=1) def addCanvasDashedWedge(self,p1,p2,p3,dash=(2,2),color=(0,0,0), color2=None,**kwargs): color = convertColor(color) dash = (4,4) pts1 = self._getLinePoints(p1,p2,dash) pts2 = self._getLinePoints(p1,p3,dash) if len(pts2)<len(pts1): pts2,pts1=pts1,pts2 for i in range(len(pts1)): self.canvas.drawLine(pts1[i][0],pts1[i][1],pts2[i][0],pts2[i][1], color=color,width=1) def flush(self): self.canvas.flush() def save(self): self.canvas.save()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Draw/spingCanvas.py", "copies": "1", "size": "3974", "license": "bsd-3-clause", "hash": -7813224031910587000, "line_mean": 32.3949579832, "line_max": 105, "alpha_frac": 0.6177654756, "autogenerated": false, "ratio": 3.1046875, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42224529755999995, "avg_score": null, "num_lines": null }
from rdkit.sping import pid import math, re from rdkit.sping.PIL.pidPIL import PILCanvas from rdkit.Chem.Draw.canvasbase import CanvasBase faceMap = {'sans': 'helvetica', 'serif': 'times'} def convertColor(color): color = pid.Color(color[0], color[1], color[2]) return color class Canvas(CanvasBase): def __init__(self, size, name, imageType='png'): if imageType == "pdf": from rdkit.sping.PDF.pidPDF import PDFCanvas as _Canvas elif imageType == "ps": from rdkit.sping.PS.pidPS import PSCanvas as _Canvas #@UnresolvedImport elif imageType == "svg": from rdkit.sping.SVG.pidSVG import SVGCanvas as _Canvas elif imageType == "png": from rdkit.sping.PIL.pidPIL import PILCanvas as _Canvas else: raise ValueError('unrecognized format: %s' % imageType) self.canvas = _Canvas(size=size, name=name) if hasattr(self.canvas, '_image'): self._image = self.canvas._image else: self._image = None self.size = size def addCanvasLine(self, p1, p2, color=(0, 0, 0), color2=None, **kwargs): if color2 and color2 != color: mp = (p1[0] + p2[0]) / 2., (p1[1] + p2[1]) / 2. color = convertColor(color) self.canvas.drawLine(p1[0], p1[1], mp[0], mp[1], color=color, width=int(kwargs.get('linewidth', 1)), dash=kwargs.get('dash', None)) color2 = convertColor(color2) self.canvas.drawLine(mp[0], mp[1], p2[0], p2[1], color=color2, width=int(kwargs.get('linewidth', 1)), dash=kwargs.get('dash', None)) else: color = convertColor(color) width = kwargs.get('linewidth', 1) self.canvas.drawLine(p1[0], p1[1], p2[0], p2[1], color=color, width=int(width), dash=kwargs.get('dash', None)) def addCanvasText(self, text, pos, font, color=(0, 0, 0), **kwargs): text = re.sub(r'\<.+?\>', '', text) font = pid.Font(face=faceMap[font.face], size=font.size) txtWidth, txtHeight = self.canvas.stringBox(text, font) bw, bh = txtWidth + txtHeight * 0.4, txtHeight * 1.4 offset = txtWidth * pos[2] labelP = pos[0] - txtWidth / 2 + offset, pos[1] + txtHeight / 2 color = convertColor(color) self.canvas.drawString(text, labelP[0], labelP[1], font, color=color) return (bw, bh, offset) def addCanvasPolygon(self, ps, color=(0, 0, 0), fill=True, stroke=False, **kwargs): if not fill and not stroke: return edgeWidth = kwargs.get('lineWidth', 0) edgeColor = pid.transparent color = convertColor(color) if not stroke: edgeWidth = 0 edgeColor = pid.transparent else: edgeWidth = kwargs.get('lineWidth', 1) edgeColor = color if not fill: fillColor = pid.transparent else: fillColor = color self.canvas.drawPolygon(ps, edgeColor=edgeColor, edgeWidth=int(edgeWidth), fillColor=fillColor, closed=1) def addCanvasDashedWedge(self, p1, p2, p3, dash=(2, 2), color=(0, 0, 0), color2=None, **kwargs): color = convertColor(color) dash = (4, 4) pts1 = self._getLinePoints(p1, p2, dash) pts2 = self._getLinePoints(p1, p3, dash) if len(pts2) < len(pts1): pts2, pts1 = pts1, pts2 for i in range(len(pts1)): self.canvas.drawLine(pts1[i][0], pts1[i][1], pts2[i][0], pts2[i][1], color=color, width=1) def flush(self): self.canvas.flush() def save(self): self.canvas.save()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Draw/spingCanvas.py", "copies": "1", "size": "3710", "license": "bsd-3-clause", "hash": 183125775615872960, "line_mean": 33.6728971963, "line_max": 99, "alpha_frac": 0.6223719677, "autogenerated": false, "ratio": 3.091666666666667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4214038634366667, "avg_score": null, "num_lines": null }
from boost import mpi from rdkit import Chem from rdkit.Chem import AllChem from rdkit.RDLogger import logger logger = logger() def dividetask(data,task,silent=True): data=mpi.broadcast(mpi.world,data,0) nProcs = mpi.world.size chunkSize=len(data)//nProcs extraBits =len(data)%nProcs res=[] allRes=[] # the root node handles the extra pieces: if mpi.world.rank == 0: for i in range(extraBits): elem=data[i] res.append(task(elem)) if not silent: logger.info('task(%d) done %d'%(mpi.world.rank,i+1)) pos=extraBits+mpi.world.rank*chunkSize; for i in range(chunkSize): elem=data[pos] pos += 1 res.append(task(elem)) if not silent: logger.info('task(%d) done %d'%(mpi.world.rank,i+1)) if mpi.world.rank==0: tmp=mpi.gather(mpi.world,res,0) for res in tmp: allRes.extend(res) else: mpi.gather(mpi.world,res,0) return allRes if __name__=='__main__': from rdkit import RDConfig import os fName = os.path.join(RDConfig.RDBaseDir,'Projects','DbCLI','testData','bzr.sdf') if mpi.world.rank==0: data = [x for x in Chem.SDMolSupplier(fName)][:50] else: data=None def generateconformations(m): m = Chem.AddHs(m) ids=AllChem.EmbedMultipleConfs(m,numConfs=10) for id in ids: AllChem.UFFOptimizeMolecule(m,confId=id) return m cms=dividetask(data,generateconformations,silent=False) # report: if mpi.world.rank==0: for i,mol in enumerate(cms): print i,mol.GetNumConformers()
{ "repo_name": "rdkit/rdkit-orig", "path": "Code/Demos/RDKit/MPI/rdkpympi.py", "copies": "2", "size": "1817", "license": "bsd-3-clause", "hash": -5639346888354662000, "line_mean": 26.5303030303, "line_max": 84, "alpha_frac": 0.6169510182, "autogenerated": false, "ratio": 3.143598615916955, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47605496341169545, "avg_score": null, "num_lines": null }
from __future__ import print_function from boost import mpi from rdkit import Chem from rdkit.Chem import AllChem from rdkit.RDLogger import logger logger = logger() def dividetask(data,task,silent=True): data=mpi.broadcast(mpi.world,data,0) nProcs = mpi.world.size chunkSize=len(data)//nProcs extraBits =len(data)%nProcs res=[] allRes=[] # the root node handles the extra pieces: if mpi.world.rank == 0: for i in range(extraBits): elem=data[i] res.append(task(elem)) if not silent: logger.info('task(%d) done %d'%(mpi.world.rank,i+1)) pos=extraBits+mpi.world.rank*chunkSize; for i in range(chunkSize): elem=data[pos] pos += 1 res.append(task(elem)) if not silent: logger.info('task(%d) done %d'%(mpi.world.rank,i+1)) if mpi.world.rank==0: tmp=mpi.gather(mpi.world,res,0) for res in tmp: allRes.extend(res) else: mpi.gather(mpi.world,res,0) return allRes if __name__=='__main__': from rdkit import RDConfig import os fName = os.path.join(RDConfig.RDBaseDir,'Projects','DbCLI','testData','bzr.sdf') if mpi.world.rank==0: data = [x for x in Chem.SDMolSupplier(fName)][:50] else: data=None def generateconformations(m): m = Chem.AddHs(m) ids=AllChem.EmbedMultipleConfs(m,numConfs=10) for id in ids: AllChem.UFFOptimizeMolecule(m,confId=id) return m cms=dividetask(data,generateconformations,silent=False) # report: if mpi.world.rank==0: for i,mol in enumerate(cms): print(i,mol.GetNumConformers())
{ "repo_name": "adalke/rdkit", "path": "Code/Demos/RDKit/MPI/rdkpympi.py", "copies": "4", "size": "1856", "license": "bsd-3-clause", "hash": -6583944413312094000, "line_mean": 26.7014925373, "line_max": 84, "alpha_frac": 0.619612069, "autogenerated": false, "ratio": 3.1564625850340136, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5776074654034014, "avg_score": null, "num_lines": null }
from __future__ import print_function from boost import mpi from rdkit import Chem from rdkit.Chem import AllChem from rdkit.RDLogger import logger logger = logger() def dividetask(data, task, silent=True): data = mpi.broadcast(mpi.world, data, 0) nProcs = mpi.world.size chunkSize = len(data) // nProcs extraBits = len(data) % nProcs res = [] allRes = [] # the root node handles the extra pieces: if mpi.world.rank == 0: for i in range(extraBits): elem = data[i] res.append(task(elem)) if not silent: logger.info('task(%d) done %d' % (mpi.world.rank, i + 1)) pos = extraBits + mpi.world.rank * chunkSize for i in range(chunkSize): elem = data[pos] pos += 1 res.append(task(elem)) if not silent: logger.info('task(%d) done %d' % (mpi.world.rank, i + 1)) if mpi.world.rank == 0: tmp = mpi.gather(mpi.world, res, 0) for res in tmp: allRes.extend(res) else: mpi.gather(mpi.world, res, 0) return allRes if __name__ == '__main__': from rdkit import RDConfig import os fName = os.path.join(RDConfig.RDBaseDir, 'Projects', 'DbCLI', 'testData', 'bzr.sdf') if mpi.world.rank == 0: data = [x for x in Chem.SDMolSupplier(fName)][:50] else: data = None def generateconformations(m): m = Chem.AddHs(m) ids = AllChem.EmbedMultipleConfs(m, numConfs=10) for id in ids: AllChem.UFFOptimizeMolecule(m, confId=id) return m cms = dividetask(data, generateconformations, silent=False) # report: if mpi.world.rank == 0: for i, mol in enumerate(cms): print(i, mol.GetNumConformers())
{ "repo_name": "rvianello/rdkit", "path": "Code/Demos/RDKit/MPI/rdkpympi.py", "copies": "5", "size": "1786", "license": "bsd-3-clause", "hash": 639885498624599900, "line_mean": 24.5142857143, "line_max": 86, "alpha_frac": 0.6438969765, "autogenerated": false, "ratio": 2.9766666666666666, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.01902771095465843, "num_lines": 70 }
from __future__ import print_function from rdkit.six.moves import cPickle from rdkit.six import iterkeys from rdkit import DataStructs,Chem from rdkit import Chem similarityMethods={'RDK':DataStructs.ExplicitBitVect, 'AtomPairs':DataStructs.IntSparseIntVect, 'TopologicalTorsions':DataStructs.LongSparseIntVect, 'Pharm2D':DataStructs.SparseBitVect, 'Gobbi2D':DataStructs.SparseBitVect, 'Morgan':DataStructs.UIntSparseIntVect, 'Avalon':DataStructs.ExplicitBitVect, } supportedSimilarityMethods=list(iterkeys(similarityMethods)) class LayeredOptions: loadLayerFlags=0xFFFFFFFF searchLayerFlags=0x7 minPath=1 maxPath=6 fpSize=1024 wordSize=32 nWords=fpSize//wordSize @staticmethod def GetFingerprint(mol,query=True): if query: flags=LayeredOptions.searchLayerFlags else: flags=LayeredOptions.loadLayerFlags return Chem.LayeredFingerprint(mol,layerFlags=flags, minPath=LayeredOptions.minPath,maxPath=LayeredOptions.maxPath, fpSize=LayeredOptions.fpSize) @staticmethod def GetWords(mol,query=True): txt = LayeredOptions.GetFingerprint(mol,query=query).ToBitString() words = [int(txt[x:x+32],2) for x in range(0,len(txt),32)] return words @staticmethod def GetQueryText(mol,query=True): words = LayeredOptions.GetWords(mol,query=query) colqs = [] for idx,word in enumerate(words): if not word: continue idx = idx+1 colqs.append('%(word)d&Col_%(idx)d=%(word)d'%locals()) return ' and '.join(colqs) def BuildSigFactory(options=None,fdefFile=None, bins=[(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,100)], skipFeats=('LumpedHydrophobe','ZnBinder')): if options: fdefFile = options.fdefFile if not fdefFile: raise ValueError('bad fdef file') from rdkit.Chem import ChemicalFeatures from rdkit.Chem.Pharm2D import SigFactory featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile) sigFactory = SigFactory.SigFactory(featFactory, skipFeats=skipFeats, trianglePruneBins=False) sigFactory.SetBins(bins) return sigFactory def BuildAtomPairFP(mol): from rdkit.Chem.AtomPairs import Pairs fp=Pairs.GetAtomPairFingerprintAsIntVect(mol) fp._sumCache = fp.GetTotalVal() return fp def BuildTorsionsFP(mol): from rdkit.Chem.AtomPairs import Torsions fp=Torsions.GetTopologicalTorsionFingerprintAsIntVect(mol) fp._sumCache = fp.GetTotalVal() return fp def BuildRDKitFP(mol): fp=Chem.RDKFingerprint(mol,nBitsPerHash=1) return fp def BuildPharm2DFP(mol): global sigFactory from rdkit.Chem.Pharm2D import Generate try: fp=Generate.Gen2DFingerprint(mol,sigFactory) except IndexError: print('FAIL:',Chem.MolToSmiles(mol,True)) raise return fp def BuildMorganFP(mol): from rdkit.Chem import rdMolDescriptors fp = rdMolDescriptors.GetMorganFingerprint(mol,2) fp._sumCache = fp.GetTotalVal() return fp def BuildAvalonFP(mol,smiles=None): from rdkit.Avalon import pyAvalonTools if smiles is None: fp=pyAvalonTools.GetAvalonFP(mol) else: fp=pyAvalonTools.GetAvalonFP(smiles,True) return fp def DepickleFP(pkl,similarityMethod): if not isinstance(pkl,(bytes,str)): pkl = str(pkl) try: klass=similarityMethods[similarityMethod] fp = klass(pkl) except Exception: import traceback traceback.print_exc() fp = cPickle.loads(pkl) return fp
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/MolDb/FingerprintUtils.py", "copies": "1", "size": "3770", "license": "bsd-3-clause", "hash": 2353405644688938500, "line_mean": 30.4166666667, "line_max": 97, "alpha_frac": 0.6790450928, "autogenerated": false, "ratio": 3.3842010771992816, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45632461699992816, "avg_score": null, "num_lines": null }
import cPickle from rdkit import DataStructs,Chem from rdkit import Chem similarityMethods={'RDK':DataStructs.ExplicitBitVect, 'AtomPairs':DataStructs.IntSparseIntVect, 'TopologicalTorsions':DataStructs.LongSparseIntVect, 'Pharm2D':DataStructs.SparseBitVect, 'Gobbi2D':DataStructs.SparseBitVect, 'Morgan':DataStructs.UIntSparseIntVect } supportedSimilarityMethods=similarityMethods.keys() class LayeredOptions: loadLayerFlags=0xFFFFFFFF searchLayerFlags=0x7 minPath=1 maxPath=6 fpSize=1024 wordSize=32 nWords=fpSize//wordSize @staticmethod def GetFingerprint(mol,query=True): if query: flags=LayeredOptions.searchLayerFlags else: flags=LayeredOptions.loadLayerFlags return Chem.LayeredFingerprint(mol,layerFlags=flags, minPath=LayeredOptions.minPath,maxPath=LayeredOptions.maxPath, fpSize=LayeredOptions.fpSize) @staticmethod def GetWords(mol,query=True): txt = LayeredOptions.GetFingerprint(mol,query=query).ToBitString() words = [int(txt[x:x+32],2) for x in range(0,len(txt),32)] return words @staticmethod def GetQueryText(mol,query=True): words = LayeredOptions.GetWords(mol,query=query) colqs = [] for idx,word in enumerate(words): if not word: continue idx = idx+1 colqs.append('%(word)d&Col_%(idx)d=%(word)d'%locals()) return ' and '.join(colqs) def BuildSigFactory(options=None,fdefFile=None, bins=[(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,100)], skipFeats=('LumpedHydrophobe','ZnBinder')): if options: fdefFile = options.fdefFile if not fdefFile: raise ValueError,'bad fdef file' from rdkit.Chem import ChemicalFeatures from rdkit.Chem.Pharm2D import SigFactory featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile) sigFactory = SigFactory.SigFactory(featFactory, skipFeats=skipFeats, trianglePruneBins=False) sigFactory.SetBins(bins) return sigFactory def BuildAtomPairFP(mol): from rdkit.Chem.AtomPairs import Pairs fp=Pairs.GetAtomPairFingerprintAsIntVect(mol) fp._sumCache = fp.GetTotalVal() return fp def BuildTorsionsFP(mol): from rdkit.Chem.AtomPairs import Torsions fp=Torsions.GetTopologicalTorsionFingerprintAsIntVect(mol) fp._sumCache = fp.GetTotalVal() return fp def BuildRDKitFP(mol): fp=Chem.RDKFingerprint(mol,nBitsPerHash=1) return fp def BuildPharm2DFP(mol): global sigFactory from rdkit.Chem.Pharm2D import Generate try: fp=Generate.Gen2DFingerprint(mol,sigFactory) except IndexError: print 'FAIL:',Chem.MolToSmiles(mol,True) raise return fp def BuildMorganFP(mol): from rdkit.Chem import rdMolDescriptors fp = rdMolDescriptors.GetMorganFingerprint(mol,2) fp._sumCache = fp.GetTotalVal() return fp def DepickleFP(pkl,similarityMethod): try: klass=similarityMethods[similarityMethod] fp = klass(pkl) except: import traceback traceback.print_exc() fp = cPickle.loads(pkl) return fp
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/MolDb/FingerprintUtils.py", "copies": "2", "size": "3319", "license": "bsd-3-clause", "hash": 985185493318015700, "line_mean": 29.7314814815, "line_max": 97, "alpha_frac": 0.6779150346, "autogenerated": false, "ratio": 3.4146090534979425, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5092524088097942, "avg_score": null, "num_lines": null }
""" Implementation of the BRICS algorithm from Degen et al. ChemMedChem *3* 1503-7 (2008) """ from __future__ import print_function import sys,re,random from rdkit import Chem from rdkit.Chem import rdChemReactions as Reactions from rdkit.six import iteritems, iterkeys, next from rdkit.six.moves import range # These are the definitions that will be applied to fragment molecules: environs = { 'L1':'[C;D3]([#0,#6,#7,#8])(=O)', # # After some discussion, the L2 definitions ("N.pl3" in the original # paper) have been removed and incorporated into a (almost) general # purpose amine definition in L5 ("N.sp3" in the paper). # # The problem is one of consistency. # Based on the original definitions you should get the following # fragmentations: # C1CCCCC1NC(=O)C -> C1CCCCC1N[2*].[1*]C(=O)C # c1ccccc1NC(=O)C -> c1ccccc1[16*].[2*]N[2*].[1*]C(=O)C # This difference just didn't make sense to us. By switching to # the unified definition we end up with: # C1CCCCC1NC(=O)C -> C1CCCCC1[15*].[5*]N[5*].[1*]C(=O)C # c1ccccc1NC(=O)C -> c1ccccc1[16*].[5*]N[5*].[1*]C(=O)C # #'L2':'[N;!R;!D1;!$(N=*)]-;!@[#0,#6]', # this one turned out to be too tricky to define above, so we set it off # in its own definition: #'L2a':'[N;D3;R;$(N(@[C;!$(C=*)])@[C;!$(C=*)])]', 'L3':'[O;D2]-;!@[#0,#6,#1]', 'L4':'[C;!D1;!$(C=*)]-;!@[#6]', #'L5':'[N;!D1;!$(N*!-*);!$(N=*);!$(N-[!C;!#0])]-[#0,C]', 'L5':'[N;!D1;!$(N=*);!$(N-[!#6;!#16;!#0;!#1]);!$([N;R]@[C;R]=O)]', 'L6':'[C;D3;!R](=O)-;!@[#0,#6,#7,#8]', 'L7a':'[C;D2,D3]-[#6]', 'L7b':'[C;D2,D3]-[#6]', '#L8':'[C;!R;!D1]-;!@[#6]', 'L8':'[C;!R;!D1;!$(C!-*)]', 'L9':'[n;+0;$(n(:[c,n,o,s]):[c,n,o,s])]', 'L10':'[N;R;$(N(@C(=O))@[C,N,O,S])]', 'L11':'[S;D2](-;!@[#0,#6])', 'L12':'[S;D4]([#6,#0])(=O)(=O)', 'L13':'[C;$(C(-;@[C,N,O,S])-;@[N,O,S])]', 'L14':'[c;$(c(:[c,n,o,s]):[n,o,s])]', 'L14b':'[c;$(c(:[c,n,o,s]):[n,o,s])]', 'L15':'[C;$(C(-;@C)-;@C)]', 'L16':'[c;$(c(:c):c)]', 'L16b':'[c;$(c(:c):c)]', } reactionDefs = ( # L1 [ ('1','3','-'), ('1','5','-'), ('1','10','-'), ], # L3 [ ('3','4','-'), ('3','13','-'), ('3','14','-'), ('3','15','-'), ('3','16','-'), ], # L4 [ ('4','5','-'), ('4','11','-'), ], # L5 [ ('5','12','-'), ('5','14','-'), ('5','16','-'), ('5','13','-'), ('5','15','-'), ], # L6 [ ('6','13','-'), ('6','14','-'), ('6','15','-'), ('6','16','-'), ], # L7 [ ('7a','7b','='), ], # L8 [ ('8','9','-'), ('8','10','-'), ('8','13','-'), ('8','14','-'), ('8','15','-'), ('8','16','-'), ], # L9 [ ('9','13','-'),# not in original paper ('9','14','-'),# not in original paper ('9','15','-'), ('9','16','-'), ], # L10 [ ('10','13','-'), ('10','14','-'), ('10','15','-'), ('10','16','-'), ], # L11 [ ('11','13','-'), ('11','14','-'), ('11','15','-'), ('11','16','-'), ], # L12 # none left # L13 [ ('13','14','-'), ('13','15','-'), ('13','16','-'), ], # L14 [ ('14','14','-'),# not in original paper ('14','15','-'), ('14','16','-'), ], # L15 [ ('15','16','-'), ], # L16 [ ('16','16','-'), # not in original paper ], ) import copy smartsGps=copy.deepcopy(reactionDefs) for gp in smartsGps: for j,defn in enumerate(gp): g1,g2,bnd = defn r1=environs['L'+g1] r2=environs['L'+g2] g1 = re.sub('[a-z,A-Z]','',g1) g2 = re.sub('[a-z,A-Z]','',g2) sma='[$(%s):1]%s;!@[$(%s):2]>>[%s*]-[*:1].[%s*]-[*:2]'%(r1,bnd,r2,g1,g2) gp[j] =sma for gp in smartsGps: for defn in gp: try: t=Reactions.ReactionFromSmarts(defn) t.Initialize() except: print(defn) raise environMatchers={} for env,sma in iteritems(environs): environMatchers[env]=Chem.MolFromSmarts(sma) bondMatchers=[] for i,compats in enumerate(reactionDefs): tmp=[] for i1,i2,bType in compats: e1 = environs['L%s'%i1] e2 = environs['L%s'%i2] patt = '[$(%s)]%s;!@[$(%s)]'%(e1,bType,e2) patt = Chem.MolFromSmarts(patt) tmp.append((i1,i2,bType,patt)) bondMatchers.append(tmp) reactions = tuple([[Reactions.ReactionFromSmarts(y) for y in x] for x in smartsGps]) reverseReactions = [] for i,rxnSet in enumerate(smartsGps): for j,sma in enumerate(rxnSet): rs,ps = sma.split('>>') sma = '%s>>%s'%(ps,rs) rxn = Reactions.ReactionFromSmarts(sma) labels = re.findall(r'\[([0-9]+?)\*\]',ps) rxn._matchers=[Chem.MolFromSmiles('[%s*]'%x) for x in labels] reverseReactions.append(rxn) def FindBRICSBonds(mol,randomizeOrder=False,silent=True): """ returns the bonds in a molecule that BRICS would cleave >>> from rdkit import Chem >>> m = Chem.MolFromSmiles('CCCOCC') >>> res = list(FindBRICSBonds(m)) >>> res [((3, 2), ('3', '4')), ((3, 4), ('3', '4'))] a more complicated case: >>> m = Chem.MolFromSmiles('CCCOCCC(=O)c1ccccc1') >>> res = list(FindBRICSBonds(m)) >>> res [((3, 2), ('3', '4')), ((3, 4), ('3', '4')), ((6, 8), ('6', '16'))] we can also randomize the order of the results: >>> random.seed(23) >>> res = list(FindBRICSBonds(m,randomizeOrder=True)) >>> sorted(res) [((3, 2), ('3', '4')), ((3, 4), ('3', '4')), ((6, 8), ('6', '16'))] Note that this is a generator function : >>> res = FindBRICSBonds(m) >>> res <generator object ...> >>> next(res) ((3, 2), ('3', '4')) >>> m = Chem.MolFromSmiles('CC=CC') >>> res = list(FindBRICSBonds(m)) >>> sorted(res) [((1, 2), ('7', '7'))] make sure we don't match ring bonds: >>> m = Chem.MolFromSmiles('O=C1NCCC1') >>> list(FindBRICSBonds(m)) [] another nice one, make sure environment 8 doesn't match something connected to a ring atom: >>> m = Chem.MolFromSmiles('CC1(C)CCCCC1') >>> list(FindBRICSBonds(m)) [] """ letter = re.compile('[a-z,A-Z]') indices = list(range(len(bondMatchers))) bondsDone=set() if randomizeOrder: random.shuffle(indices,random=random.random) envMatches={} for env,patt in iteritems(environMatchers): envMatches[env]=mol.HasSubstructMatch(patt) for gpIdx in indices: if randomizeOrder: compats =bondMatchers[gpIdx][:] random.shuffle(compats,random=random.random) else: compats = bondMatchers[gpIdx] for i1,i2,bType,patt in compats: if not envMatches['L'+i1] or not envMatches['L'+i2]: continue matches = mol.GetSubstructMatches(patt) i1 = letter.sub('',i1) i2 = letter.sub('',i2) for match in matches: if match not in bondsDone and (match[1],match[0]) not in bondsDone: bondsDone.add(match) yield(((match[0],match[1]),(i1,i2))) def BreakBRICSBonds(mol,bonds=None,sanitize=True,silent=True): """ breaks the BRICS bonds in a molecule and returns the results >>> from rdkit import Chem >>> m = Chem.MolFromSmiles('CCCOCC') >>> m2=BreakBRICSBonds(m) >>> Chem.MolToSmiles(m2,True) '[3*]O[3*].[4*]CC.[4*]CCC' a more complicated case: >>> m = Chem.MolFromSmiles('CCCOCCC(=O)c1ccccc1') >>> m2=BreakBRICSBonds(m) >>> Chem.MolToSmiles(m2,True) '[3*]O[3*].[4*]CCC.[4*]CCC([6*])=O.[16*]c1ccccc1' can also specify a limited set of bonds to work with: >>> m = Chem.MolFromSmiles('CCCOCC') >>> m2 = BreakBRICSBonds(m,[((3, 2), ('3', '4'))]) >>> Chem.MolToSmiles(m2,True) '[3*]OCC.[4*]CCC' this can be used as an alternate approach for doing a BRICS decomposition by following BreakBRICSBonds with a call to Chem.GetMolFrags: >>> m = Chem.MolFromSmiles('CCCOCC') >>> m2=BreakBRICSBonds(m) >>> frags = Chem.GetMolFrags(m2,asMols=True) >>> [Chem.MolToSmiles(x,True) for x in frags] ['[4*]CCC', '[3*]O[3*]', '[4*]CC'] """ if not bonds: #bonds = FindBRICSBonds(mol) res = Chem.FragmentOnBRICSBonds(mol) if sanitize: Chem.SanitizeMol(res) return res eMol = Chem.EditableMol(mol) nAts = mol.GetNumAtoms() dummyPositions=[] for indices,dummyTypes in bonds: ia,ib = indices obond = mol.GetBondBetweenAtoms(ia,ib) bondType=obond.GetBondType() eMol.RemoveBond(ia,ib) da,db = dummyTypes atoma = Chem.Atom(0) atoma.SetIsotope(int(da)) atoma.SetNoImplicit(True) idxa = nAts nAts+=1 eMol.AddAtom(atoma) eMol.AddBond(ia,idxa,bondType) atomb = Chem.Atom(0) atomb.SetIsotope(int(db)) atomb.SetNoImplicit(True) idxb = nAts nAts+=1 eMol.AddAtom(atomb) eMol.AddBond(ib,idxb,bondType) if mol.GetNumConformers(): dummyPositions.append((idxa,ib)) dummyPositions.append((idxb,ia)) res = eMol.GetMol() if sanitize: Chem.SanitizeMol(res) if mol.GetNumConformers(): for conf in mol.GetConformers(): resConf = res.GetConformer(conf.GetId()) for ia,pa in dummyPositions: resConf.SetAtomPosition(ia,conf.GetAtomPosition(pa)) return res def BRICSDecompose(mol,allNodes=None,minFragmentSize=1,onlyUseReactions=None, silent=True,keepNonLeafNodes=False,singlePass=False,returnMols=False): """ returns the BRICS decomposition for a molecule >>> from rdkit import Chem >>> m = Chem.MolFromSmiles('CCCOCc1cc(c2ncccc2)ccc1') >>> res = list(BRICSDecompose(m)) >>> sorted(res) ['[14*]c1ccccn1', '[16*]c1cccc([16*])c1', '[3*]O[3*]', '[4*]CCC', '[4*]C[8*]'] >>> res = list(BRICSDecompose(m,returnMols=True)) >>> res[0] <rdkit.Chem.rdchem.Mol object ...> >>> smis = [Chem.MolToSmiles(x,True) for x in res] >>> sorted(smis) ['[14*]c1ccccn1', '[16*]c1cccc([16*])c1', '[3*]O[3*]', '[4*]CCC', '[4*]C[8*]'] nexavar, an example from the paper (corrected): >>> m = Chem.MolFromSmiles('CNC(=O)C1=NC=CC(OC2=CC=C(NC(=O)NC3=CC(=C(Cl)C=C3)C(F)(F)F)C=C2)=C1') >>> res = list(BRICSDecompose(m)) >>> sorted(res) ['[1*]C([1*])=O', '[1*]C([6*])=O', '[14*]c1cc([16*])ccn1', '[16*]c1ccc(Cl)c([16*])c1', '[16*]c1ccc([16*])cc1', '[3*]O[3*]', '[5*]NC', '[5*]N[5*]', '[8*]C(F)(F)F'] it's also possible to keep pieces that haven't been fully decomposed: >>> m = Chem.MolFromSmiles('CCCOCC') >>> res = list(BRICSDecompose(m,keepNonLeafNodes=True)) >>> sorted(res) ['CCCOCC', '[3*]OCC', '[3*]OCCC', '[3*]O[3*]', '[4*]CC', '[4*]CCC'] >>> m = Chem.MolFromSmiles('CCCOCc1cc(c2ncccc2)ccc1') >>> res = list(BRICSDecompose(m,keepNonLeafNodes=True)) >>> sorted(res) ['CCCOCc1cccc(-c2ccccn2)c1', '[14*]c1ccccn1', '[16*]c1cccc(-c2ccccn2)c1', '[16*]c1cccc(COCCC)c1', '[16*]c1cccc([16*])c1', '[3*]OCCC', '[3*]OC[8*]', '[3*]OCc1cccc(-c2ccccn2)c1', '[3*]OCc1cccc([16*])c1', '[3*]O[3*]', '[4*]CCC', '[4*]C[8*]', '[4*]Cc1cccc(-c2ccccn2)c1', '[4*]Cc1cccc([16*])c1', '[8*]COCCC'] or to only do a single pass of decomposition: >>> m = Chem.MolFromSmiles('CCCOCc1cc(c2ncccc2)ccc1') >>> res = list(BRICSDecompose(m,singlePass=True)) >>> sorted(res) ['CCCOCc1cccc(-c2ccccn2)c1', '[14*]c1ccccn1', '[16*]c1cccc(-c2ccccn2)c1', '[16*]c1cccc(COCCC)c1', '[3*]OCCC', '[3*]OCc1cccc(-c2ccccn2)c1', '[4*]CCC', '[4*]Cc1cccc(-c2ccccn2)c1', '[8*]COCCC'] setting a minimum size for the fragments: >>> m = Chem.MolFromSmiles('CCCOCC') >>> res = list(BRICSDecompose(m,keepNonLeafNodes=True,minFragmentSize=2)) >>> sorted(res) ['CCCOCC', '[3*]OCC', '[3*]OCCC', '[4*]CC', '[4*]CCC'] >>> m = Chem.MolFromSmiles('CCCOCC') >>> res = list(BRICSDecompose(m,keepNonLeafNodes=True,minFragmentSize=3)) >>> sorted(res) ['CCCOCC', '[3*]OCC', '[4*]CCC'] >>> res = list(BRICSDecompose(m,minFragmentSize=2)) >>> sorted(res) ['[3*]OCC', '[3*]OCCC', '[4*]CC', '[4*]CCC'] """ global reactions mSmi = Chem.MolToSmiles(mol,1) if allNodes is None: allNodes=set() if mSmi in allNodes: return set() activePool={mSmi:mol} allNodes.add(mSmi) foundMols={mSmi:mol} for gpIdx,reactionGp in enumerate(reactions): newPool = {} while activePool: matched=False nSmi = next(iterkeys(activePool)) mol = activePool.pop(nSmi) for rxnIdx,reaction in enumerate(reactionGp): if onlyUseReactions and (gpIdx,rxnIdx) not in onlyUseReactions: continue if not silent: print('--------') print(smartsGps[gpIdx][rxnIdx]) ps = reaction.RunReactants((mol,)) if ps: if not silent: print(nSmi,'->',len(ps),'products') for prodSeq in ps: seqOk=True # we want to disqualify small fragments, so sort the product sequence by size tSeq = [(prod.GetNumAtoms(onlyExplicit=True),idx) for idx,prod in enumerate(prodSeq)] tSeq.sort() for nats,idx in tSeq: prod = prodSeq[idx] try: Chem.SanitizeMol(prod) except: continue pSmi = Chem.MolToSmiles(prod,1) if minFragmentSize>0: nDummies = pSmi.count('*') if nats-nDummies<minFragmentSize: seqOk=False break prod.pSmi = pSmi ts = [(x,prodSeq[y]) for x,y in tSeq] prodSeq=ts if seqOk: matched=True for nats,prod in prodSeq: pSmi = prod.pSmi #print('\t',nats,pSmi) if pSmi not in allNodes: if not singlePass: activePool[pSmi] = prod allNodes.add(pSmi) foundMols[pSmi]=prod if singlePass or keepNonLeafNodes or not matched: newPool[nSmi]=mol activePool = newPool if not (singlePass or keepNonLeafNodes): if not returnMols: res = set(activePool.keys()) else: res = activePool.values() else: if not returnMols: res = allNodes else: res = foundMols.values() return res import random dummyPattern=Chem.MolFromSmiles('[*]') def BRICSBuild(fragments,onlyCompleteMols=True,seeds=None,uniquify=True, scrambleReagents=True,maxDepth=3): seen = set() if not seeds: seeds = list(fragments) if scrambleReagents: seeds = list(seeds) random.shuffle(seeds,random=random.random) if scrambleReagents: tempReactions = list(reverseReactions) random.shuffle(tempReactions,random=random.random) else: tempReactions=reverseReactions for seed in seeds: seedIsR1=False seedIsR2=False nextSteps=[] for rxn in tempReactions: if seed.HasSubstructMatch(rxn._matchers[0]): seedIsR1=True if seed.HasSubstructMatch(rxn._matchers[1]): seedIsR2=True for fragment in fragments: ps = None if fragment.HasSubstructMatch(rxn._matchers[0]): if seedIsR2: ps = rxn.RunReactants((fragment,seed)) if fragment.HasSubstructMatch(rxn._matchers[1]): if seedIsR1: ps = rxn.RunReactants((seed,fragment)) if ps: for p in ps: if uniquify: pSmi =Chem.MolToSmiles(p[0],True) if pSmi in seen: continue else: seen.add(pSmi) if p[0].HasSubstructMatch(dummyPattern): nextSteps.append(p[0]) if not onlyCompleteMols: yield p[0] else: yield p[0] if nextSteps and maxDepth>0: for p in BRICSBuild(fragments,onlyCompleteMols=onlyCompleteMols, seeds=nextSteps,uniquify=uniquify, maxDepth=maxDepth-1): if uniquify: pSmi =Chem.MolToSmiles(p,True) if pSmi in seen: continue else: seen.add(pSmi) yield p # ------- ------- ------- ------- ------- ------- ------- ------- # Begin testing code #------------------------------------ # # doctest boilerplate # def _test(): import doctest,sys return doctest.testmod(sys.modules["__main__"], optionflags=doctest.ELLIPSIS+doctest.NORMALIZE_WHITESPACE) if __name__=='__main__': import unittest class TestCase(unittest.TestCase): def test1(self): m = Chem.MolFromSmiles('CC(=O)OC') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==2) m = Chem.MolFromSmiles('CC(=O)N1CCC1=O') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==2,res) m = Chem.MolFromSmiles('c1ccccc1N(C)C') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==2,res) m = Chem.MolFromSmiles('c1cccnc1N(C)C') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==2,res) m = Chem.MolFromSmiles('o1ccnc1N(C)C') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==2) m = Chem.MolFromSmiles('c1ccccc1OC') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==2) m = Chem.MolFromSmiles('o1ccnc1OC') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==2) m = Chem.MolFromSmiles('O1CCNC1OC') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==2) m = Chem.MolFromSmiles('CCCSCC') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==3,res) self.assertTrue('[11*]S[11*]' in res,res) m = Chem.MolFromSmiles('CCNC(=O)C1CC1') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==4,res) self.assertTrue('[5*]N[5*]' in res,res) def test2(self): # example from the paper, nexavar: m = Chem.MolFromSmiles('CNC(=O)C1=NC=CC(OC2=CC=C(NC(=O)NC3=CC(=C(Cl)C=C3)C(F)(F)F)C=C2)=C1') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==9,res) def test3(self): m = Chem.MolFromSmiles('FC(F)(F)C1=C(Cl)C=CC(NC(=O)NC2=CC=CC=C2)=C1') res = BRICSDecompose(m) self.assertTrue(res) self.assertTrue(len(res)==5,res) self.assertTrue('[5*]N[5*]' in res,res) self.assertTrue('[16*]c1ccccc1' in res,res) self.assertTrue('[8*]C(F)(F)F' in res,res) def test4(self): allNodes = set() m = Chem.MolFromSmiles('c1ccccc1OCCC') res = BRICSDecompose(m,allNodes=allNodes) self.assertTrue(res) leaves=res self.assertTrue(len(leaves)==3,leaves) self.assertTrue(len(allNodes)==6,allNodes) res = BRICSDecompose(m,allNodes=allNodes) self.assertFalse(res) self.assertTrue(len(allNodes)==6,allNodes) m = Chem.MolFromSmiles('c1ccccc1OCCCC') res = BRICSDecompose(m,allNodes=allNodes) self.assertTrue(res) leaves.update(res) self.assertTrue(len(allNodes)==9,allNodes) self.assertTrue(len(leaves)==4,leaves) m = Chem.MolFromSmiles('c1cc(C(=O)NCC)ccc1OCCC') res = BRICSDecompose(m,allNodes=allNodes) self.assertTrue(res) leaves.update(res) self.assertTrue(len(leaves)==8,leaves) self.assertTrue(len(allNodes)==18,allNodes) def test5(self): allNodes = set() frags = [ '[14*]c1ncncn1', '[16*]c1ccccc1', '[14*]c1ncccc1', ] frags = [Chem.MolFromSmiles(x) for x in frags] res = BRICSBuild(frags) self.assertTrue(res) res= list(res) self.assertTrue(len(res)==6) smis = [Chem.MolToSmiles(x,True) for x in res] self.assertTrue('c1ccc(-c2ccccc2)cc1' in smis) self.assertTrue('c1ccc(-c2ccccn2)cc1' in smis) def test5a(self): allNodes = set() frags = [ '[3*]O[3*]', '[16*]c1ccccc1', ] frags = [Chem.MolFromSmiles(x) for x in frags] res = BRICSBuild(frags) self.assertTrue(res) res=list(res) smis = [Chem.MolToSmiles(x,True) for x in res] self.assertTrue(len(smis)==2,smis) self.assertTrue('c1ccc(Oc2ccccc2)cc1' in smis) self.assertTrue('c1ccc(-c2ccccc2)cc1' in smis) def test6(self): allNodes = set() frags = [ '[16*]c1ccccc1', '[3*]OC', '[9*]n1cccc1', ] frags = [Chem.MolFromSmiles(x) for x in frags] res = BRICSBuild(frags) self.assertTrue(res) res= list(res) self.assertTrue(len(res)==3) smis = [Chem.MolToSmiles(x,True) for x in res] self.assertTrue('c1ccc(-c2ccccc2)cc1' in smis) self.assertTrue('COc1ccccc1' in smis) self.assertTrue('c1ccn(-c2ccccc2)c1' in smis) def test7(self): allNodes = set() frags = [ '[16*]c1ccccc1', '[3*]OC', '[3*]OCC(=O)[6*]', ] frags = [Chem.MolFromSmiles(x) for x in frags] res = BRICSBuild(frags) self.assertTrue(res) res= list(res) smis = [Chem.MolToSmiles(x,True) for x in res] self.assertTrue(len(res)==3) self.assertTrue('c1ccc(-c2ccccc2)cc1' in smis) self.assertTrue('COc1ccccc1' in smis) self.assertTrue('O=C(COc1ccccc1)c1ccccc1' in smis) def test8(self): random.seed(23) base = Chem.MolFromSmiles("n1cncnc1OCC(C1CC1)OC1CNC1") catalog = BRICSDecompose(base) self.assertTrue(len(catalog)==5,catalog) catalog = [Chem.MolFromSmiles(x) for x in catalog] ms = [Chem.MolToSmiles(x) for x in BRICSBuild(catalog,maxDepth=4)] self.assertTrue(len(ms)==36,ms) ts = ['n1cnc(C2CNC2)nc1','n1cnc(-c2ncncn2)nc1','C(OC1CNC1)C(C1CC1)OC1CNC1', 'n1cnc(OC(COC2CNC2)C2CC2)nc1','n1cnc(OCC(OC2CNC2)C2CNC2)nc1'] ts = [Chem.MolToSmiles(Chem.MolFromSmiles(x),True) for x in ts] for t in ts: self.assertTrue(t in ms,(t,ms)) def test9(self): m = Chem.MolFromSmiles('CCOc1ccccc1c1ncc(c2nc(NCCCC)ncn2)cc1') res=BRICSDecompose(m) self.assertEqual(len(res),7) self.assertTrue('[3*]O[3*]' in res) self.assertFalse('[14*]c1ncnc(NCCCC)n1' in res) res = BRICSDecompose(m,singlePass=True) self.assertEqual(len(res),13) self.assertTrue('[3*]OCC' in res) self.assertTrue('[14*]c1ncnc(NCCCC)n1' in res) def test10(self): m = Chem.MolFromSmiles('C1CCCCN1c1ccccc1') res=BRICSDecompose(m) self.assertEqual(len(res),2,res) def test11(self): # test coordinate preservation: molblock=""" RDKit 3D 13 14 0 0 0 0 0 0 0 0999 V2000 -1.2004 0.5900 0.6110 C 0 0 0 0 0 0 0 0 0 0 0 0 -2.2328 1.3173 0.0343 C 0 0 0 0 0 0 0 0 0 0 0 0 -3.4299 0.6533 -0.1500 C 0 0 0 0 0 0 0 0 0 0 0 0 -3.3633 -0.7217 -0.3299 C 0 0 0 0 0 0 0 0 0 0 0 0 -2.1552 -1.3791 -0.2207 C 0 0 0 0 0 0 0 0 0 0 0 0 -1.1425 -0.7969 0.5335 C 0 0 0 0 0 0 0 0 0 0 0 0 0.1458 -1.4244 0.4108 O 0 0 0 0 0 0 0 0 0 0 0 0 1.2976 -0.7398 -0.1026 C 0 0 0 0 0 0 0 0 0 0 0 0 2.4889 -0.7939 0.5501 N 0 0 0 0 0 0 0 0 0 0 0 0 3.4615 0.1460 0.3535 C 0 0 0 0 0 0 0 0 0 0 0 0 3.0116 1.4034 -0.0296 C 0 0 0 0 0 0 0 0 0 0 0 0 1.9786 1.4264 -0.9435 C 0 0 0 0 0 0 0 0 0 0 0 0 1.1399 0.3193 -0.9885 C 0 0 0 0 0 0 0 0 0 0 0 0 1 2 2 0 2 3 1 0 3 4 2 0 4 5 1 0 5 6 2 0 6 7 1 0 7 8 1 0 8 9 2 0 9 10 1 0 10 11 2 0 11 12 1 0 12 13 2 0 6 1 1 0 13 8 1 0 M END """ m = Chem.MolFromMolBlock(molblock) pieces = BreakBRICSBonds(m) frags = Chem.GetMolFrags(pieces,asMols=True) self.assertEqual(len(frags),3) self.assertEqual(frags[0].GetNumAtoms(),7) self.assertEqual(frags[1].GetNumAtoms(),3) self.assertEqual(frags[2].GetNumAtoms(),7) c1 = m.GetConformer() c2 = frags[0].GetConformer() for i in range(6): p1 = c1.GetAtomPosition(i) p2 = c2.GetAtomPosition(i) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(6) p2 = c2.GetAtomPosition(6) self.assertEqual((p1-p2).Length(),0.0) c2 = frags[2].GetConformer() for i in range(6): p1 = c1.GetAtomPosition(i+7) p2 = c2.GetAtomPosition(i) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(6) p2 = c2.GetAtomPosition(6) self.assertEqual((p1-p2).Length(),0.0) c2 = frags[1].GetConformer() for i in range(1): p1 = c1.GetAtomPosition(i+6) p2 = c2.GetAtomPosition(i) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(5) p2 = c2.GetAtomPosition(1) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(6) p2 = c2.GetAtomPosition(0) self.assertEqual((p1-p2).Length(),0.0) # make sure multiple conformations (include 2D) also work: molblock=""" RDKit 2D 13 14 0 0 0 0 0 0 0 0999 V2000 -1.2990 -0.8654 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -2.5981 -1.6154 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -3.8971 -0.8654 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -3.8971 0.6346 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -2.5981 1.3846 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -1.2990 0.6346 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.0000 1.3846 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 1.2990 0.6346 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 1.2990 -0.8654 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0 2.5981 -1.6154 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 3.8971 -0.8654 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 3.8971 0.6346 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 2.5981 1.3846 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 1 2 2 0 2 3 1 0 3 4 2 0 4 5 1 0 5 6 2 0 6 7 1 0 7 8 1 0 8 9 2 0 9 10 1 0 10 11 2 0 11 12 1 0 12 13 2 0 6 1 1 0 13 8 1 0 M END """ m2 = Chem.MolFromMolBlock(molblock) m.AddConformer(m2.GetConformer(),assignId=True) self.assertEqual(m.GetNumConformers(),2) pieces = BreakBRICSBonds(m) frags = Chem.GetMolFrags(pieces,asMols=True) self.assertEqual(len(frags),3) self.assertEqual(frags[0].GetNumAtoms(),7) self.assertEqual(frags[1].GetNumAtoms(),3) self.assertEqual(frags[2].GetNumAtoms(),7) self.assertEqual(frags[0].GetNumConformers(),2) self.assertEqual(frags[1].GetNumConformers(),2) self.assertEqual(frags[2].GetNumConformers(),2) c1 = m.GetConformer(0) c2 = frags[0].GetConformer(0) for i in range(6): p1 = c1.GetAtomPosition(i) p2 = c2.GetAtomPosition(i) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(6) p2 = c2.GetAtomPosition(6) self.assertEqual((p1-p2).Length(),0.0) c2 = frags[2].GetConformer(0) for i in range(6): p1 = c1.GetAtomPosition(i+7) p2 = c2.GetAtomPosition(i) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(6) p2 = c2.GetAtomPosition(6) self.assertEqual((p1-p2).Length(),0.0) c2 = frags[1].GetConformer(0) for i in range(1): p1 = c1.GetAtomPosition(i+6) p2 = c2.GetAtomPosition(i) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(5) p2 = c2.GetAtomPosition(1) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(6) p2 = c2.GetAtomPosition(0) self.assertEqual((p1-p2).Length(),0.0) c1 = m.GetConformer(1) c2 = frags[0].GetConformer(1) for i in range(6): p1 = c1.GetAtomPosition(i) p2 = c2.GetAtomPosition(i) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(6) p2 = c2.GetAtomPosition(6) self.assertEqual((p1-p2).Length(),0.0) c2 = frags[2].GetConformer(1) for i in range(6): p1 = c1.GetAtomPosition(i+7) p2 = c2.GetAtomPosition(i) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(6) p2 = c2.GetAtomPosition(6) self.assertEqual((p1-p2).Length(),0.0) c2 = frags[1].GetConformer(1) for i in range(1): p1 = c1.GetAtomPosition(i+6) p2 = c2.GetAtomPosition(i) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(5) p2 = c2.GetAtomPosition(1) self.assertEqual((p1-p2).Length(),0.0) p1 = c1.GetAtomPosition(6) p2 = c2.GetAtomPosition(0) self.assertEqual((p1-p2).Length(),0.0) def test12(self): m = Chem.MolFromSmiles('CCS(=O)(=O)NCC') res=list(FindBRICSBonds(m)) self.assertEqual(len(res),2,res) atIds = [x[0] for x in res] atIds.sort() self.assertEqual(atIds,[(5,2), (6,5)]) failed,tried = _test() if failed: sys.exit(failed) unittest.main()
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/BRICS.py", "copies": "1", "size": "30884", "license": "bsd-3-clause", "hash": 8657458389479379000, "line_mean": 30.2591093117, "line_max": 305, "alpha_frac": 0.564046108, "autogenerated": false, "ratio": 2.638530542503204, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37025766505032043, "avg_score": null, "num_lines": null }
import math class CanvasBase: """Base class for specialized canvas backends""" def addCanvasLine(self, p1, p2, color=(0, 0, 0), color2=None, **kwargs): """Draw a single line on the canvas This function will draw a line between `p1` and `p2` with the given `color`. If `color2` is specified, it will be used to draw the second half of the segment """ raise NotImplementedError, 'This should be implemented' def addCanvasText(self, text, pos, font, color=(0, 0, 0), **kwargs): """Draw some text The provided `text` is drawn at position `pos` using the given `font` and the chosen `color`. """ raise NotImplementedError, 'This should be implemented' def addCanvasPolygon(self, ps, color=(0, 0 ,0), **kwargs): """Draw a polygon Draw a polygon identified by vertexes given in `ps` using the given `color` """ raise NotImplementedError, 'This should be implemented' def addCanvasDashedWedge(self, p1, p2, p3, dash=(2, 2), color=(0, 0, 0), color2=None, **kwargs): """Draw a dashed wedge The wedge is identified by the three points `p1`, `p2`, and `p3`. It will be drawn using the given `color`; if `color2` is specified it will be used for the second half of the wedge TODO: fix comment, I'm not sure what `dash` does """ raise NotImplementedError, 'This should be implemented' def flush(self): """Complete any remaining draw operation This is supposed to be the last operation on the canvas before saving it """ raise NotImplementedError, 'This should be implemented' def _getLinePoints(self, p1, p2, dash): x1, y1 = p1 x2, y2 = p2 dx = x2 - x1 dy = y2 - y1 lineLen = math.sqrt(dx * dx + dy * dy) theta = math.atan2(dy, dx) cosT = math.cos(theta) sinT = math.sin(theta) pos = (x1, y1) pts = [pos] dist = 0 currDash = 0 while dist < lineLen: currL = dash[currDash % len(dash)] if (dist + currL > lineLen): currL = lineLen - dist endP = (pos[0] + currL * cosT, pos[1] + currL * sinT) pts.append(endP) pos = endP dist += currL currDash += 1 return pts
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Draw/canvasbase.py", "copies": "2", "size": "2756", "license": "bsd-3-clause", "hash": 2977427300148829000, "line_mean": 31.0465116279, "line_max": 77, "alpha_frac": 0.5674891147, "autogenerated": false, "ratio": 3.82246879334258, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.538995790804258, "avg_score": null, "num_lines": null }
import math class CanvasBase: """Base class for specialized canvas backends""" def addCanvasLine(self, p1, p2, color=(0, 0, 0), color2=None, **kwargs): """Draw a single line on the canvas This function will draw a line between `p1` and `p2` with the given `color`. If `color2` is specified, it will be used to draw the second half of the segment """ raise NotImplementedError('This should be implemented') def addCanvasText(self, text, pos, font, color=(0, 0, 0), **kwargs): """Draw some text The provided `text` is drawn at position `pos` using the given `font` and the chosen `color`. """ raise NotImplementedError('This should be implemented') def addCanvasPolygon(self, ps, color=(0, 0, 0), **kwargs): """Draw a polygon Draw a polygon identified by vertexes given in `ps` using the given `color` """ raise NotImplementedError('This should be implemented') def addCanvasDashedWedge(self, p1, p2, p3, dash=(2, 2), color=(0, 0, 0), color2=None, **kwargs): """Draw a dashed wedge The wedge is identified by the three points `p1`, `p2`, and `p3`. It will be drawn using the given `color`; if `color2` is specified it will be used for the second half of the wedge TODO: fix comment, I'm not sure what `dash` does """ raise NotImplementedError('This should be implemented') def flush(self): """Complete any remaining draw operation This is supposed to be the last operation on the canvas before saving it """ raise NotImplementedError('This should be implemented') def _getLinePoints(self, p1, p2, dash): x1, y1 = p1 x2, y2 = p2 dx = x2 - x1 dy = y2 - y1 lineLen = math.sqrt(dx * dx + dy * dy) theta = math.atan2(dy, dx) cosT = math.cos(theta) sinT = math.sin(theta) pos = (x1, y1) pts = [pos] dist = 0 currDash = 0 while dist < lineLen: currL = dash[currDash % len(dash)] if (dist + currL > lineLen): currL = lineLen - dist endP = (pos[0] + currL * cosT, pos[1] + currL * sinT) pts.append(endP) pos = endP dist += currL currDash += 1 return pts
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Draw/canvasbase.py", "copies": "1", "size": "2583", "license": "bsd-3-clause", "hash": -7351523442940886000, "line_mean": 28.6896551724, "line_max": 98, "alpha_frac": 0.6054974835, "autogenerated": false, "ratio": 3.6125874125874127, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9689663076128023, "avg_score": 0.005684363991877772, "num_lines": 87 }
from rdkit import Chem import os,re from rdkit import RDConfig class SaltRemover(object): defnFilename=os.path.join(RDConfig.RDDataDir,'Salts.txt') defnData = None salts = None def __init__(self,defnFilename=None,defnData=None): if defnFilename: self.defnFilename = defnFilename self.defnData = defnData self._initPatterns() def _initPatterns(self): """ >>> remover = SaltRemover() >>> len(remover.salts)>0 True >>> remover = SaltRemover(defnData="[Cl,Br]") >>> len(remover.salts) 1 """ whitespace = re.compile(r'[\t ]+') if self.defnData: from cStringIO import StringIO inF = StringIO(self.defnData) else: inF = file(self.defnFilename,'r') self.salts = [] for line in inF: line = line.strip().split('//')[0] if line: splitL = whitespace.split(line) try: salt = Chem.MolFromSmarts(splitL[0]) except: import traceback traceback.print_exc() raise ValueError,line self.salts.append(salt) def StripMol(self,mol,dontRemoveEverything=False): """ >>> remover = SaltRemover(defnData="[Cl,Br]") >>> len(remover.salts) 1 >>> mol = Chem.MolFromSmiles('CN(C)C.Cl') >>> res = remover.StripMol(mol) >>> res is not None True >>> res.GetNumAtoms() 4 Notice that all salts are removed: >>> mol = Chem.MolFromSmiles('CN(C)C.Cl.Cl.Br') >>> res = remover.StripMol(mol) >>> res.GetNumAtoms() 4 Matching (e.g. "salt-like") atoms in the molecule are unchanged: >>> mol = Chem.MolFromSmiles('CN(Br)Cl') >>> res = remover.StripMol(mol) >>> res.GetNumAtoms() 4 >>> mol = Chem.MolFromSmiles('CN(Br)Cl.Cl') >>> res = remover.StripMol(mol) >>> res.GetNumAtoms() 4 Charged salts are handled reasonably: >>> mol = Chem.MolFromSmiles('C[NH+](C)(C).[Cl-]') >>> res = remover.StripMol(mol) >>> res.GetNumAtoms() 4 Watch out for this case (everything removed): >>> remover = SaltRemover() >>> len(remover.salts)>1 True >>> mol = Chem.MolFromSmiles('CC(=O)O.[Na]') >>> res = remover.StripMol(mol) >>> res.GetNumAtoms() 0 dontRemoveEverything helps with this by leaving the last salt: >>> res = remover.StripMol(mol,dontRemoveEverything=True) >>> res.GetNumAtoms() 4 but in cases where the last salts are the same, it can't choose between them, so it returns all of them: >>> mol = Chem.MolFromSmiles('Cl.Cl') >>> res = remover.StripMol(mol,dontRemoveEverything=True) >>> res.GetNumAtoms() 2 """ def _applyPattern(m,salt,notEverything): nAts = m.GetNumAtoms() if not nAts: return m res = m t = Chem.DeleteSubstructs(res,salt,True) if not t or (notEverything and t.GetNumAtoms()==0): return res; else: res = t while res.GetNumAtoms() and nAts>res.GetNumAtoms(): nAts = res.GetNumAtoms() t = Chem.DeleteSubstructs(res,salt,True) if notEverything and t.GetNumAtoms()==0: break else: res = t return res if dontRemoveEverything and len(Chem.GetMolFrags(mol))<=1: return mol modified=False for i,salt in enumerate(self.salts): tMol = _applyPattern(mol,salt,dontRemoveEverything) if tMol is not mol: mol = tMol modified=True if dontRemoveEverything and len(Chem.GetMolFrags(mol))<=1: break if modified and mol.GetNumAtoms()>0: Chem.SanitizeMol(mol) return mol def __call__(self,mol,dontRemoveEverything=False): """ >>> remover = SaltRemover(defnData="[Cl,Br]") >>> len(remover.salts) 1 >>> mol = Chem.MolFromSmiles('CN(C)C.Cl') >>> res = remover(mol) >>> res is not None True >>> res.GetNumAtoms() 4 """ return self.StripMol(mol,dontRemoveEverything=dontRemoveEverything) #------------------------------------ # # doctest boilerplate # def _test(): import doctest,sys return doctest.testmod(sys.modules["__main__"]) if __name__ == '__main__': import sys failed,tried = _test() sys.exit(failed)
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/SaltRemover.py", "copies": "2", "size": "5928", "license": "bsd-3-clause", "hash": -5253783833529496000, "line_mean": 27.9170731707, "line_max": 86, "alpha_frac": 0.6417004049, "autogenerated": false, "ratio": 3.4385150812064964, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9990690761740257, "avg_score": 0.017904944873247793, "num_lines": 205 }
from __future__ import print_function import unittest, os import os.path from rdkit import RDConfig from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import FunctionalGroups class TestCase(unittest.TestCase): def test1Basics(self): txt = """ AcidChloride\tC(=O)Cl\tAcid Chloride AcidChloride.Benzoyl\tC(=O)(Cl)c1ccccc1\tBenzoyl Amine\tN\tAmine Amine.Primary\t[N;H2]\tPrimary Amine.Primary.Aromatic\t[N;H2][a]\tPrimary Aromatic Amine.Aromatic\tN[a]\tAromatic """ hierarchy = FunctionalGroups.BuildFuncGroupHierarchy(data=txt) self.assertTrue(hierarchy) self.assertTrue(len(hierarchy) == 2) self.assertTrue(len(hierarchy[0]) == 2) self.assertTrue(len(hierarchy[1]) == 4) self.assertTrue(hierarchy[0].name == 'Acid Chloride') self.assertTrue(hierarchy[0].children[0].name == 'Benzoyl') self.assertTrue(hierarchy[0].label == 'AcidChloride') self.assertTrue(hierarchy[0].rxnSmarts == '') m = Chem.MolFromSmiles('ClC(=O)CCCNc1ccccc1') fp = FunctionalGroups.CreateMolFingerprint(m, hierarchy) self.assertTrue(fp == [1, 0, 1, 0, 0, 1]) m = Chem.MolFromSmiles('OC(=O)CCC') fp = FunctionalGroups.CreateMolFingerprint(m, hierarchy) self.assertTrue(fp == [0, 0, 0, 0, 0, 0]) # make sure we get the same hierarchy on the second call: hierarchy = FunctionalGroups.BuildFuncGroupHierarchy(data=txt) self.assertTrue(hierarchy) self.assertTrue(len(hierarchy) == 2) self.assertTrue(len(hierarchy[0]) == 2) self.assertTrue(len(hierarchy[1]) == 4) self.assertTrue(hierarchy[0].name == 'Acid Chloride') self.assertTrue(hierarchy[0].children[0].name == 'Benzoyl') self.assertTrue(hierarchy[0].label == 'AcidChloride') self.assertTrue(hierarchy[0].rxnSmarts == '') # if we edit this hierarchy it doesn't affect the global one: hierarchy.pop(0) self.assertTrue(len(hierarchy[0]) == 4) hierarchy = FunctionalGroups.BuildFuncGroupHierarchy(data=txt) self.assertTrue(hierarchy) self.assertTrue(len(hierarchy) == 2) self.assertTrue(len(hierarchy[0]) == 2) self.assertTrue(len(hierarchy[1]) == 4) self.assertTrue(hierarchy[0].name == 'Acid Chloride') self.assertTrue(hierarchy[0].children[0].name == 'Benzoyl') self.assertTrue(hierarchy[0].label == 'AcidChloride') self.assertTrue(hierarchy[0].rxnSmarts == '') # and if we edit the global one and don't force, we get the edited one: FunctionalGroups.hierarchy.pop(0) self.assertTrue(len(FunctionalGroups.hierarchy[0]) == 4) hierarchy = FunctionalGroups.BuildFuncGroupHierarchy(data=txt) self.assertTrue(hierarchy) self.assertTrue(len(hierarchy) == 1) self.assertTrue(len(hierarchy[0]) == 4) # but a force gets us back: hierarchy = FunctionalGroups.BuildFuncGroupHierarchy(data=txt, force=True) self.assertTrue(len(hierarchy) == 2) self.assertTrue(len(hierarchy[0]) == 2) self.assertTrue(len(hierarchy[1]) == 4) def test2Comments(self): txt = """ AcidChloride\tC(=O)Cl\tAcid Chloride AcidChloride.Benzoyl\tC(=O)(Cl)c1ccccc1\tBenzoyl Amine\tN\tAmine Amine.Primary\t[N;H2]\tPrimary //Amine.Primary.Aromatic\t[N;H2][a]\tPrimary Aromatic Amine.Aromatic\tN[a]\tAromatic """ hierarchy = FunctionalGroups.BuildFuncGroupHierarchy(data=txt) self.assertTrue(hierarchy) self.assertTrue(len(hierarchy) == 2) self.assertTrue(len(hierarchy[0]) == 2) self.assertTrue(len(hierarchy[1]) == 3) def test3Reactions(self): txt = """BoronicAcid\t[$(B-!@[#6])](O)(O)\tBoronic Acid\t[#6:1][B:2]([O:3])[O:4]>>[#6:1].[B:2]([O:3])[O:4] BoronicAcid.Aromatic\t[$(B-!@c)](O)(O)\tAromatic\t[c:1][B:2]([O:3])[O:4]>>[c:1].[B:2]([O:3])[O:4] BoronicAcid.Aliphatic\t[$(B-!@C)](O)(O)\tAliphatic\t[C:1][B:2]([O:3])[O:4]>>[C:1].[B:2]([O:3])[O:4] """ hierarchy = FunctionalGroups.BuildFuncGroupHierarchy(data=txt) self.assertTrue(hierarchy) self.assertTrue(len(hierarchy) == 1) self.assertTrue(len(hierarchy[0].children) == 2) self.assertTrue(hierarchy[0].rxnSmarts != '') self.assertTrue(hierarchy[0].children[0].rxnSmarts != '') def test4Hs(self): hierarchy = FunctionalGroups.BuildFuncGroupHierarchy() inName = os.path.join(RDConfig.RDCodeDir, 'Chem', 'test_data', 'NCI_5K_TPSA.csv') with open(inName, 'r') as inF: lines = inF.readlines() ms = [Chem.MolFromSmiles(x.split(',')[0]) for x in lines if x[0] != '#'] for m in ms: mh = Chem.AddHs(m) fp = FunctionalGroups.CreateMolFingerprint(m, hierarchy) fph = FunctionalGroups.CreateMolFingerprint(mh, hierarchy) if fp != fph: print(fp.ToBitString()) print(fph.ToBitString()) self.assertEqual(fp, fph) if __name__ == '__main__': import sys, getopt, re doLong = 0 if len(sys.argv) > 1: args, extras = getopt.getopt(sys.argv[1:], 'l') for arg, val in args: if arg == '-l': doLong = 1 sys.argv.remove('-l') if doLong: for methName in dir(TestCase): if re.match('_test', methName): newName = re.sub('_test', 'test', methName) exec('TestCase.%s = TestCase.%s' % (newName, methName)) unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/UnitTestFunctionalGroups.py", "copies": "1", "size": "6890", "license": "bsd-3-clause", "hash": -6626148680066144000, "line_mean": 40.0119047619, "line_max": 110, "alpha_frac": 0.6918722787, "autogenerated": false, "ratio": 3.176579068695251, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43684513473952513, "avg_score": null, "num_lines": null }
from rdkit import RDConfig import os,weakref,cStringIO,re class FGHierarchyNode(object): children=None name="" label="" pattern=None smarts="" rxnSmarts="" parent=None removalReaction=None def __init__(self,name,patt,smarts="",label="",rxnSmarts="",parent=None): self.name=name self.pattern=patt if parent: self.parent=weakref.ref(parent) self.label=label self.smarts=smarts self.children = [] self.rxnSmarts=rxnSmarts def __len__(self): res = 1 for child in self.children: res += len(child) return res class FuncGroupFileParseError(ValueError): pass groupDefns = {} hierarchy=None lastData=None lastFilename=None def BuildFuncGroupHierarchy(fileNm=None,data=None,force=False): global groupDefns,hierarchy,lastData,lastFilename if not force and hierarchy and (not data or data==lastData) and \ (not fileNm or fileNm==lastFilename): return hierarchy[:] lastData=data splitter = re.compile('\t+') from rdkit import Chem if not fileNm and not data: fileNm = os.path.join(RDConfig.RDDataDir,'Functional_Group_Hierarchy.txt') if fileNm: inF = file(fileNm,'r') lastFilename = fileNm elif data: inF = cStringIO.StringIO(data) else: raise ValueError,"need data or filename" groupDefns={} res = [] lineNo=0 for line in inF.readlines(): lineNo+=1 line=line.strip() line = line.split('//')[0] if not line: continue splitL = splitter.split(line) if len(splitL)<3: raise FuncGroupFileParseError,"Input line %d (%s) is not long enough."%(lineNo,repr(line)) label = splitL[0].strip() if groupDefns.has_key(label): raise FuncGroupFileParseError,"Duplicate label on line %d."%lineNo labelHierarchy = label.split('.') if len(labelHierarchy)>1: for i in range(len(labelHierarchy)-1): tmp = '.'.join(labelHierarchy[:i+1]) if not groupDefns.has_key(tmp): raise FuncGroupFileParseError,"Hierarchy member %s (line %d) not found."%(tmp,lineNo) parent = groupDefns['.'.join(labelHierarchy[:-1])] else: parent = None smarts = splitL[1] try: patt = Chem.MolFromSmarts(smarts) except: import traceback traceback.print_exc() patt = None if not patt: raise FuncGroupFileParseError,'Smarts "%s" (line %d) could not be parsed.'%(smarts,lineNo) name = splitL[2].strip() rxnSmarts='' if len(splitL)>3: rxnSmarts=splitL[3] node = FGHierarchyNode(name,patt,smarts=smarts,label=label,parent=parent,rxnSmarts=rxnSmarts) if parent: parent.children.append(node) else: res.append(node) groupDefns[label] = node hierarchy=res[:] return res def _SetNodeBits(mol,node,res,idx): ms = mol.GetSubstructMatches(node.pattern) count = 0 seen = {} for m in ms: if m[0] not in seen: count+=1 seen[m[0]] = 1 if count: res[idx] = count idx += 1 for child in node.children: idx=_SetNodeBits(mol,child,res,idx) else: idx += len(node) return idx def CreateMolFingerprint(mol,hierarchy): totL = 0 for entry in hierarchy: totL += len(entry) res = [0]*totL idx = 0 for entry in hierarchy: idx = _SetNodeBits(mol,entry,res,idx) return res
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/FunctionalGroups.py", "copies": "2", "size": "5012", "license": "bsd-3-clause", "hash": 550083384094856800, "line_mean": 29.5609756098, "line_max": 97, "alpha_frac": 0.6889465283, "autogenerated": false, "ratio": 3.6031631919482385, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.05011290202067399, "num_lines": 164 }
import os,weakref,re from rdkit.six.moves import cStringIO as StringIO from rdkit import RDConfig class FGHierarchyNode(object): children=None name="" label="" pattern=None smarts="" rxnSmarts="" parent=None removalReaction=None def __init__(self,name,patt,smarts="",label="",rxnSmarts="",parent=None): self.name=name self.pattern=patt if parent: self.parent=weakref.ref(parent) self.label=label self.smarts=smarts self.children = [] self.rxnSmarts=rxnSmarts def __len__(self): res = 1 for child in self.children: res += len(child) return res class FuncGroupFileParseError(ValueError): pass groupDefns = {} hierarchy=None lastData=None lastFilename=None def BuildFuncGroupHierarchy(fileNm=None,data=None,force=False): global groupDefns,hierarchy,lastData,lastFilename if not force and hierarchy and (not data or data==lastData) and \ (not fileNm or fileNm==lastFilename): return hierarchy[:] lastData=data splitter = re.compile('\t+') from rdkit import Chem if not fileNm and not data: fileNm = os.path.join(RDConfig.RDDataDir,'Functional_Group_Hierarchy.txt') if fileNm: inF = open(fileNm,'r') lastFilename = fileNm elif data: inF = StringIO(data) else: raise ValueError("need data or filename") groupDefns={} res = [] lineNo=0 for line in inF.readlines(): lineNo+=1 line=line.strip() line = line.split('//')[0] if not line: continue splitL = splitter.split(line) if len(splitL)<3: raise FuncGroupFileParseError("Input line %d (%s) is not long enough."%(lineNo,repr(line))) label = splitL[0].strip() if label in groupDefns: raise FuncGroupFileParseError("Duplicate label on line %d."%lineNo) labelHierarchy = label.split('.') if len(labelHierarchy)>1: for i in range(len(labelHierarchy)-1): tmp = '.'.join(labelHierarchy[:i+1]) if not tmp in groupDefns: raise FuncGroupFileParseError("Hierarchy member %s (line %d) not found."%(tmp,lineNo)) parent = groupDefns['.'.join(labelHierarchy[:-1])] else: parent = None smarts = splitL[1] patt = Chem.MolFromSmarts(smarts) if not patt: raise FuncGroupFileParseError('Smarts "%s" (line %d) could not be parsed.'%(smarts,lineNo)) name = splitL[2].strip() rxnSmarts='' if len(splitL)>3: rxnSmarts=splitL[3] node = FGHierarchyNode(name,patt,smarts=smarts,label=label,parent=parent,rxnSmarts=rxnSmarts) if parent: parent.children.append(node) else: res.append(node) groupDefns[label] = node hierarchy=res[:] return res def _SetNodeBits(mol,node,res,idx): ms = mol.GetSubstructMatches(node.pattern) count = 0 seen = {} for m in ms: if m[0] not in seen: count+=1 seen[m[0]] = 1 if count: res[idx] = count idx += 1 for child in node.children: idx=_SetNodeBits(mol,child,res,idx) else: idx += len(node) return idx def CreateMolFingerprint(mol,hierarchy): totL = 0 for entry in hierarchy: totL += len(entry) res = [0]*totL idx = 0 for entry in hierarchy: idx = _SetNodeBits(mol,entry,res,idx) return res
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/FunctionalGroups.py", "copies": "1", "size": "4943", "license": "bsd-3-clause", "hash": 1837077783234519600, "line_mean": 29.89375, "line_max": 97, "alpha_frac": 0.6918875177, "autogenerated": false, "ratio": 3.608029197080292, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9555269656373975, "avg_score": 0.0489294116812635, "num_lines": 160 }
import os, weakref, re from rdkit.six.moves import cStringIO as StringIO from rdkit import RDConfig class FGHierarchyNode(object): children = None name = "" label = "" pattern = None smarts = "" rxnSmarts = "" parent = None removalReaction = None def __init__(self, name, patt, smarts="", label="", rxnSmarts="", parent=None): self.name = name self.pattern = patt if parent: self.parent = weakref.ref(parent) self.label = label self.smarts = smarts self.children = [] self.rxnSmarts = rxnSmarts def __len__(self): res = 1 for child in self.children: res += len(child) return res class FuncGroupFileParseError(ValueError): pass groupDefns = {} hierarchy = None lastData = None lastFilename = None def BuildFuncGroupHierarchy(fileNm=None, data=None, force=False): global groupDefns, hierarchy, lastData, lastFilename if not force and hierarchy and (not data or data==lastData) and \ (not fileNm or fileNm==lastFilename): return hierarchy[:] lastData = data splitter = re.compile('\t+') from rdkit import Chem if not fileNm and not data: fileNm = os.path.join(RDConfig.RDDataDir, 'Functional_Group_Hierarchy.txt') if fileNm: inF = open(fileNm, 'r') lastFilename = fileNm elif data: inF = StringIO(data) else: raise ValueError("need data or filename") groupDefns = {} res = [] lineNo = 0 for line in inF.readlines(): lineNo += 1 line = line.strip() line = line.split('//')[0] if not line: continue splitL = splitter.split(line) if len(splitL) < 3: raise FuncGroupFileParseError("Input line %d (%s) is not long enough." % (lineNo, repr(line))) label = splitL[0].strip() if label in groupDefns: raise FuncGroupFileParseError("Duplicate label on line %d." % lineNo) labelHierarchy = label.split('.') if len(labelHierarchy) > 1: for i in range(len(labelHierarchy) - 1): tmp = '.'.join(labelHierarchy[:i + 1]) if not tmp in groupDefns: raise FuncGroupFileParseError("Hierarchy member %s (line %d) not found." % (tmp, lineNo)) parent = groupDefns['.'.join(labelHierarchy[:-1])] else: parent = None smarts = splitL[1] patt = Chem.MolFromSmarts(smarts) if not patt: raise FuncGroupFileParseError('Smarts "%s" (line %d) could not be parsed.' % (smarts, lineNo)) name = splitL[2].strip() rxnSmarts = '' if len(splitL) > 3: rxnSmarts = splitL[3] node = FGHierarchyNode(name, patt, smarts=smarts, label=label, parent=parent, rxnSmarts=rxnSmarts) if parent: parent.children.append(node) else: res.append(node) groupDefns[label] = node hierarchy = res[:] return res def _SetNodeBits(mol, node, res, idx): ms = mol.GetSubstructMatches(node.pattern) count = 0 seen = {} for m in ms: if m[0] not in seen: count += 1 seen[m[0]] = 1 if count: res[idx] = count idx += 1 for child in node.children: idx = _SetNodeBits(mol, child, res, idx) else: idx += len(node) return idx def CreateMolFingerprint(mol, hierarchy): totL = 0 for entry in hierarchy: totL += len(entry) res = [0] * totL idx = 0 for entry in hierarchy: idx = _SetNodeBits(mol, entry, res, idx) return res
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/FunctionalGroups.py", "copies": "1", "size": "5073", "license": "bsd-3-clause", "hash": -4769319122137447000, "line_mean": 29.1964285714, "line_max": 100, "alpha_frac": 0.6741573034, "autogenerated": false, "ratio": 3.6628158844765344, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9726112919799372, "avg_score": 0.022172053615432348, "num_lines": 168 }
""" unit testing code for molecule drawing """ from rdkit import RDConfig import unittest,os,tempfile from rdkit import Chem from rdkit.Chem import Draw from rdkit.RDLogger import logger logger = logger() class TestCase(unittest.TestCase): def setUp(self): self.mol = Chem.MolFromSmiles('c1c(C[15NH3+])ccnc1[C@](Cl)(Br)[C@](Cl)(Br)F') def testCairoFile(self): try: from rdkit.Chem.Draw.cairoCanvas import Canvas except ImportError: logger.info("Skipping cairo test") return os.environ['RDKIT_CANVAS']='cairo' foo,fn=tempfile.mkstemp(suffix='.png') foo=None self.assertEqual(os.path.getsize(fn),0) Draw.MolToFile(self.mol,fn) self.assertNotEqual(os.path.getsize(fn),0) try: os.unlink(fn) except: pass def testAggFile(self): try: from rdkit.Chem.Draw.aggCanvas import Canvas except ImportError: logger.info("Skipping agg test") return os.environ['RDKIT_CANVAS']='agg' foo,fn=tempfile.mkstemp(suffix='.png') foo=None self.assertEqual(os.path.getsize(fn),0) Draw.MolToFile(self.mol,fn) self.assertNotEqual(os.path.getsize(fn),0) try: os.unlink(fn) except: pass def testSpingFile(self): try: from rdkit.Chem.Draw.spingCanvas import Canvas except ImportError: logger.info("Skipping sping test") return os.environ['RDKIT_CANVAS']='sping' foo,fn=tempfile.mkstemp(suffix='.png') foo=None self.assertEqual(os.path.getsize(fn),0) Draw.MolToFile(self.mol,fn) self.assertNotEqual(os.path.getsize(fn),0) try: os.unlink(fn) except: pass def testCairoImage(self): try: from rdkit.Chem.Draw.cairoCanvas import Canvas except ImportError: return os.environ['RDKIT_CANVAS']='cairo' img=Draw.MolToImage(self.mol,size=(300,300)) self.assertTrue(img) self.assertEqual(img.size[0],300) self.assertEqual(img.size[1],300) def testAggImage(self): try: from rdkit.Chem.Draw.aggCanvas import Canvas except ImportError: return os.environ['RDKIT_CANVAS']='agg' img=Draw.MolToImage(self.mol,size=(300,300)) self.assertTrue(img) self.assertEqual(img.size[0],300) self.assertEqual(img.size[1],300) def testSpingImage(self): try: from rdkit.Chem.Draw.spingCanvas import Canvas except ImportError: return os.environ['RDKIT_CANVAS']='sping' img=Draw.MolToImage(self.mol,size=(300,300)) self.assertTrue(img) self.assertEqual(img.size[0],300) self.assertEqual(img.size[1],300) def testQtImage(self): import sys try: from PySide import QtGui from rdkit.Chem.Draw.qtCanvas import Canvas except ImportError: return app = QtGui.QApplication(sys.argv) img = Draw.MolToQPixmap(self.mol, size=(300, 300)) self.assertTrue(img) self.assertEqual(img.size().height(), 300) self.assertEqual(img.size().width(), 300) def testCairoImageDash(self): try: from rdkit.Chem.Draw.cairoCanvas import Canvas except ImportError: return os.environ['RDKIT_CANVAS']='cairo' img=Draw.MolToImage(self.mol,size=(300,300),kekulize=False) self.assertTrue(img) self.assertEqual(img.size[0],300) self.assertEqual(img.size[1],300) def testAggImageDash(self): try: from rdkit.Chem.Draw.aggCanvas import Canvas except ImportError: return os.environ['RDKIT_CANVAS']='agg' img=Draw.MolToImage(self.mol,size=(300,300),kekulize=False) self.assertTrue(img) self.assertEqual(img.size[0],300) self.assertEqual(img.size[1],300) def testSpingImageDash(self): try: from rdkit.Chem.Draw.spingCanvas import Canvas except ImportError: return os.environ['RDKIT_CANVAS']='sping' img=Draw.MolToImage(self.mol,size=(300,300),kekulize=False) self.assertTrue(img) self.assertEqual(img.size[0],300) self.assertEqual(img.size[1],300) def testGithubIssue54(self): try: from rdkit.Chem.Draw.spingCanvas import Canvas except ImportError: return os.environ['RDKIT_CANVAS']='sping' mol = Chem.MolFromSmiles('c1([O])ccc(O)cc1') img = Draw.MolToImage(mol) self.assertTrue(img) def testGithubIssue86(self): mol = Chem.MolFromSmiles('F[C@H](Cl)Br') for b in mol.GetBonds(): self.assertEqual(b.GetBondDir(),Chem.BondDir.NONE) img = Draw.MolToImage(mol,kekulize=False) self.assertTrue(img) for b in mol.GetBonds(): self.assertEqual(b.GetBondDir(),Chem.BondDir.NONE) Chem.WedgeMolBonds(mol,mol.GetConformer()) obds = [x.GetBondDir() for x in mol.GetBonds()] self.assertEqual(obds.count(Chem.BondDir.NONE),2) img = Draw.MolToImage(mol,kekulize=False) self.assertTrue(img) nbds = [x.GetBondDir() for x in mol.GetBonds()] self.assertEqual(obds,nbds) if __name__ == '__main__': unittest.main()
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/Draw/UnitTestDraw.py", "copies": "3", "size": "5233", "license": "bsd-3-clause", "hash": 4157226426166414000, "line_mean": 25.4292929293, "line_max": 81, "alpha_frac": 0.6674947449, "autogenerated": false, "ratio": 3.1167361524717094, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.03287489741308486, "num_lines": 198 }
from __future__ import print_function from rdkit.Chem import * from rdkit import RDConfig from rdkit.Chem import rdDepictor import unittest import gzip import tempfile import os import gzip from subprocess import Popen, PIPE import re import io import sys from rdkit.rdBase import DisableLog, EnableLog from rdkit.six.moves.cPickle import loads curdir = os.path.dirname(os.path.abspath(__file__)) esc = chr(27) red = esc + '[31m' green = esc + '[32m' reset = esc + '[0m' class NoReentrySDMolSupplier(object): def __init__(self, filepath, sanitize=False): self.ms = SDMolSupplier() self.valid = True self.filepath = filepath self.f = self.fileopen() self.sanitize = sanitize def fileopen(self): return file(self.filepath, 'r') def fileclose(self): if self.f: self.f.close() def reset(self): self.fileclose() self.f = gzip.open(self.filepath, 'r') self.valid = True def next(self): buf = '' for line in self.f: line = str(line) buf += line if line.strip() == '$$$$': break if buf: self.sdf = buf self.ms.SetData(buf, sanitize=self.sanitize, removeHs=False) return self.ms[0] else: self.fileclose() self.f = None raise StopIteration def dumpCurMol(self): f = file(self.ms[0].GetProp('PUBCHEM_COMPOUND_CID') + '.sdf', 'w') f.write(self.sdf) f.close() return f.name def __iter__(self): if not self.valid: raise ValueError("No reentry allowed") self.valid = False return self def __next__(self): return self.next() class GzippedSDMolSupplier(NoReentrySDMolSupplier): def fileopen(self): return gzip.open(self.filepath, 'r') def inchiDiffPrefix(inchi1, inchi2): inchi1 = inchi1.split('/') inchi2 = inchi2.split('/') for i in range(len(inchi1) + 1): if i == len(inchi1): break if i == len(inchi2) or inchi1[i] != inchi2[i]: break if len(inchi1) >= i: return inchi1[i][0] else: return inchi2[i][0] def inchiDiff(inchi1, inchi2): inchi1 = inchi1.split('/') inchi2 = inchi2.split('/') for i in range(len(inchi1) + 1): if i == len(inchi1): break if i == len(inchi2) or inchi1[i] != inchi2[i]: break return '/'.join(inchi1[:i]) + red + '/' + '/'.join(inchi1[i:]) + \ '\n' + reset + \ '/'.join(inchi2[:i]) + red + '/' + '/'.join(inchi2[i:]) + \ reset class RegressionTest(unittest.TestCase): def testPrechloricAcid(self): examples = ( ('OCl(=O)(=O)=O', 'InChI=1S/ClHO4/c2-1(3,4)5/h(H,2,3,4,5)'), ('CC1=CC2=NCC(CN2C=C1)C(=O)c3ccc4cc(C)ccc4c3.OCl(=O)(=O)=O', 'InChI=1S/C21H20N2O.ClHO4/c1-14-3-4-17-11-18(6-5-16(17)9-14)21(24)19-12-22-20-10-15(2)7-8-23(20)13-19;2-1(3,4)5/h3-11,19H,12-13H2,1-2H3;(H,2,3,4,5)'), ('CNc1ccc2nc3ccccc3[n+](C)c2c1.[O-]Cl(=O)(=O)=O', 'InChI=1S/C14H13N3.ClHO4/c1-15-10-7-8-12-14(9-10)17(2)13-6-4-3-5-11(13)16-12;2-1(3,4)5/h3-9H,1-2H3;(H,2,3,4,5)'), ) for smiles, expected in examples: m = MolFromSmiles(smiles) inchi = MolToInchi(m) self.assertEqual(inchi, expected) class TestCase(unittest.TestCase): def setUp(self): self.dataset = dict() self.dataset_inchi = dict() inf = gzip.open(os.path.join(RDConfig.RDCodeDir, 'Chem/test_data', 'pubchem-hard-set.sdf.gz'),'r') self.dataset['problematic'] = ForwardSDMolSupplier(inf,sanitize=False,removeHs=False) with open(os.path.join(RDConfig.RDCodeDir, 'Chem/test_data', 'pubchem-hard-set.inchi'),'r') as intF: buf = intF.read().replace('\r\n', '\n').encode('latin1') intF.close() with io.BytesIO(buf) as inF: pkl = inF.read() self.dataset_inchi['problematic'] = loads(pkl,encoding='latin1') # disable logging DisableLog('rdApp.warning') def tearDown(self): EnableLog('rdApp.warning') def test0InchiWritePubChem(self): for fp, f in self.dataset.items(): inchi_db = self.dataset_inchi[fp] same, diff, reasonable = 0, 0, 0 for i_,m in enumerate(f): if m is None: continue ref_inchi = inchi_db[m.GetProp('PUBCHEM_COMPOUND_CID')] x, y = MolToInchi(m), ref_inchi if x != y: if re.search(r'.[1-9]?ClO4', x) is not None: reasonable += 1 continue SanitizeMol(m) if filter(lambda i: i >= 8, [len(r) for r in m.GetRingInfo().AtomRings()]): reasonable += 1 continue # if it is because RDKit does not think the bond is stereo z = MolToInchi(MolFromMolBlock(MolToMolBlock(m))) if y != z and inchiDiffPrefix(y, z) == 'b': reasonable += 1 continue # some warning try: MolToInchi(m, treatWarningAsError=True) except InchiReadWriteError as inst: inchi, error = inst.args if 'Metal' in error: reasonable += 1 continue diff += 1 print('InChI mismatch for PubChem Compound ' + m.GetProp('PUBCHEM_COMPOUND_CID') + '\n' + MolToSmiles(m,True) + '\n' + inchiDiff(x, y)) print() else: same += 1 print(green + "InChI write Summary: %d identical, %d suffix variance, %d reasonable" % (same, diff, reasonable) + reset) self.assertEqual(same, 1164) self.assertEqual(diff, 0) self.assertEqual(reasonable, 17) def test1InchiReadPubChem(self): for fp, f in self.dataset.items(): inchi_db = self.dataset_inchi[fp] same, diff, reasonable = 0, 0, 0 for m in f: if m is None: continue ref_inchi = inchi_db[m.GetProp('PUBCHEM_COMPOUND_CID')] cid = m.GetProp('PUBCHEM_COMPOUND_CID') x = MolToInchi(m) try: y = MolToInchi( MolFromSmiles( MolToSmiles( MolFromInchi(x), isomericSmiles=True ) ) ) except Exception: y = '' if y == '': # metal involved? try: MolToInchi(m, treatWarningAsError=True) except InchiReadWriteError as inst: _, error = inst.args if 'Metal' in error or \ 'Charges were rearranged' in error: reasonable += 1 continue # RDKit does not like the SMILES? use MolBlock instead inchiMol = MolFromInchi(x) if inchiMol: rdDepictor.Compute2DCoords(inchiMol) z = MolToInchi(MolFromMolBlock(MolToMolBlock(inchiMol))) if x == z: reasonable += 1 continue # InChI messed up the radical? unsanitizedInchiMol = MolFromInchi(x, sanitize=False) if sum([a.GetNumRadicalElectrons() * a.GetAtomicNum() for a in m.GetAtoms() if a.GetNumRadicalElectrons() != 0] ) != sum([a.GetNumRadicalElectrons() * a.GetAtomicNum() for a in unsanitizedInchiMol.GetAtoms() if a.GetNumRadicalElectrons() != 0]): reasonable += 1 continue diff += 1 print(green + 'Empty mol for PubChem Compound ' + cid + '\n' + reset) continue if x != y: # if there was warning in the first place, then this is # tolerable try: MolToInchi(m, treatWarningAsError=True) MolFromInchi(x, treatWarningAsError=True) except InchiReadWriteError as inst: reasonable += 1 continue # or if there are big rings SanitizeMol(m) if filter(lambda i: i >= 8, [len(r) for r in m.GetRingInfo().AtomRings()]): reasonable += 1 continue # or if RDKit loses bond stereo s = MolToSmiles(m, True) if MolToSmiles(MolFromSmiles(s), True) != s: reasonable += 1 continue # or if it is RDKit SMILES writer unhappy about the mol inchiMol = MolFromInchi(x) rdDepictor.Compute2DCoords(inchiMol) z = MolToInchi(MolFromMolBlock(MolToMolBlock(inchiMol))) if x == z: reasonable += 1 continue diff += 1 print(green + 'Molecule mismatch for PubChem Compound ' + cid + '\n' + reset + inchiDiff(x, y) + reset) print() else: same += 1 print(green + "InChI Read Summary: %d identical, %d variance, %d reasonable variance" % (same, diff, reasonable) + reset) self.assertEqual(same, 620) self.assertEqual(diff, 0) self.assertEqual(reasonable, 561) def test2InchiOptions(self): m = MolFromSmiles("CC=C(N)C") inchi1 = MolToInchi(m).split('/', 1)[1] inchi2 = MolToInchi(m, "/SUU").split('/', 1)[1] self.assertEqual(inchi1 + '/b4-3?', inchi2) def test3InchiKey(self): inchi = 'InChI=1S/C9H12/c1-2-6-9-7-4-3-5-8-9/h3-5,7-8H,2,6H2,1H3' self.assertEqual(InchiToInchiKey(inchi), 'ODLMAHJVESYWTB-UHFFFAOYSA-N') if __name__ == '__main__': # only run the test if InChI is available if inchi.INCHI_AVAILABLE: unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/UnitTestInchi.py", "copies": "1", "size": "12794", "license": "bsd-3-clause", "hash": 2785738550371971000, "line_mean": 38.6099071207, "line_max": 170, "alpha_frac": 0.512740347, "autogenerated": false, "ratio": 3.7094810089881123, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9683359744338452, "avg_score": 0.007772322329932038, "num_lines": 323 }
from rdkit.Chem import * from rdkit import RDConfig from rdkit.Chem import rdDepictor import unittest import gzip import tempfile import os import gzip from subprocess import Popen, PIPE import re from rdkit.rdBase import DisableLog, EnableLog from pickle import load curdir = os.path.dirname(os.path.abspath(__file__)) esc = chr(27) red = esc + '[31m' green = esc + '[32m' reset = esc + '[0m' class NoReentrySDMolSupplier(object): def __init__(self, filepath, sanitize=False): self.ms = SDMolSupplier() self.valid = True self.filepath = filepath self.f = self.fileopen() self.sanitize = sanitize def fileopen(self): return file(self.filepath, 'r') def fileclose(self): if self.f: self.f.close() def reset(self): self.fileclose() self.f = gzip.open(self.filepath, 'r') self.valid = True def next(self): buf = '' for line in self.f: buf += line if line.strip() == '$$$$': break if buf: self.sdf = buf self.ms.SetData(buf, sanitize=self.sanitize, removeHs=False) return self.ms[0] else: self.fileclose() self.f = None raise StopIteration def dumpCurMol(self): f = file(self.ms[0].GetProp('PUBCHEM_COMPOUND_CID') + '.sdf', 'w') f.write(self.sdf) f.close() return f.name def __iter__(self): if not self.valid: raise ValueError("No reentry allowed") self.valid = False return self class GzippedSDMolSupplier(NoReentrySDMolSupplier): def fileopen(self): return gzip.open(self.filepath, 'r') def inchiDiffPrefix(inchi1, inchi2): inchi1 = inchi1.split('/') inchi2 = inchi2.split('/') for i in range(len(inchi1) + 1): if i == len(inchi1): break if i == len(inchi2) or inchi1[i] != inchi2[i]: break if len(inchi1) >= i: return inchi1[i][0] else: return inchi2[i][0] def inchiDiff(inchi1, inchi2): inchi1 = inchi1.split('/') inchi2 = inchi2.split('/') for i in range(len(inchi1) + 1): if i == len(inchi1): break if i == len(inchi2) or inchi1[i] != inchi2[i]: break return '/'.join(inchi1[:i]) + red + '/' + '/'.join(inchi1[i:]) + \ '\n' + reset + \ '/'.join(inchi2[:i]) + red + '/' + '/'.join(inchi2[i:]) + \ reset class RegressionTest(unittest.TestCase): def testPrechloricAcid(self): examples = ( ('OCl(=O)(=O)=O', 'InChI=1S/ClHO4/c2-1(3,4)5/h(H,2,3,4,5)'), ('CC1=CC2=NCC(CN2C=C1)C(=O)c3ccc4cc(C)ccc4c3.OCl(=O)(=O)=O', 'InChI=1S/C21H20N2O.ClHO4/c1-14-3-4-17-11-18(6-5-16(17)9-14)21(24)19-12-22-20-10-15(2)7-8-23(20)13-19;2-1(3,4)5/h3-11,19H,12-13H2,1-2H3;(H,2,3,4,5)'), ('CNc1ccc2nc3ccccc3[n+](C)c2c1.[O-]Cl(=O)(=O)=O', 'InChI=1S/C14H13N3.ClHO4/c1-15-10-7-8-12-14(9-10)17(2)13-6-4-3-5-11(13)16-12;2-1(3,4)5/h3-9H,1-2H3;(H,2,3,4,5)'), ) for smiles, expected in examples: m = MolFromSmiles(smiles) inchi = MolToInchi(m) self.assertEqual(inchi, expected) class TestCase(unittest.TestCase): def setUp(self): self.dataset = dict() self.dataset_inchi = dict() self.dataset['problematic'] = GzippedSDMolSupplier( os.path.join(RDConfig.RDCodeDir, 'Chem/test_data', 'pubchem-hard-set.sdf.gz')) _ = file(os.path.join(RDConfig.RDCodeDir, 'Chem/test_data', 'pubchem-hard-set.inchi')) self.dataset_inchi['problematic'] = load(_) _.close() # disable logging DisableLog('rdApp.warning') def tearDown(self): EnableLog('rdApp.warning') def test0InchiWritePubChem(self): for fp, f in self.dataset.items(): inchi_db = self.dataset_inchi[fp] same, diff, reasonable = 0, 0, 0 for m in f: if m is None: continue ref_inchi = inchi_db[m.GetProp('PUBCHEM_COMPOUND_CID')] x, y = MolToInchi(m), ref_inchi if x != y: if re.search(r'.[1-9]?ClO4', x) is not None: reasonable += 1 continue SanitizeMol(m) if filter(lambda i: i >= 8, [len(r) for r in m.GetRingInfo().AtomRings()]): reasonable += 1 continue # if it is because RDKit does not think the bond is stereo z = MolToInchi(MolFromMolBlock(MolToMolBlock(m))) if y != z and inchiDiffPrefix(y, z) == 'b': reasonable += 1 continue # some warning try: MolToInchi(m, treatWarningAsError=True) except InchiReadWriteError as inst: inchi, error = inst if 'Metal' in error: reasonable += 1 continue diff += 1 print 'InChI mismatach for PubChem Compound ' + \ m.GetProp('PUBCHEM_COMPOUND_CID') + \ '\n' + MolToSmiles(m) + '\n' + inchiDiff(x, y) print else: same += 1 print green + "InChI write Summary: %d identical, %d suffix variance, %d reasonable" % (same, diff, reasonable) + reset self.assertEqual(same, 1164) self.assertEqual(diff, 0) self.assertEqual(reasonable, 17) def test1InchiReadPubChem(self): for fp, f in self.dataset.items(): inchi_db = self.dataset_inchi[fp] same, diff, reasonable = 0, 0, 0 for m in f: if m is None: continue ref_inchi = inchi_db[m.GetProp('PUBCHEM_COMPOUND_CID')] cid = m.GetProp('PUBCHEM_COMPOUND_CID') x = MolToInchi(m) try: y = MolToInchi( MolFromSmiles( MolToSmiles( MolFromInchi(x), isomericSmiles=True ) ) ) except: y = '' if y == '': # metal involved? try: MolToInchi(m, treatWarningAsError=True) except InchiReadWriteError as inst: _, error = inst if 'Metal' in error or \ 'Charges were rearranged' in error: reasonable += 1 continue # RDKit does not like the SMILES? use MolBlock instead inchiMol = MolFromInchi(x) if inchiMol: rdDepictor.Compute2DCoords(inchiMol) z = MolToInchi(MolFromMolBlock(MolToMolBlock(inchiMol))) if x == z: reasonable += 1 continue # InChI messed up the radical? unsanitizedInchiMol = MolFromInchi(x, sanitize=False) if sum([a.GetNumRadicalElectrons() * a.GetAtomicNum() for a in m.GetAtoms() if a.GetNumRadicalElectrons() != 0] ) != sum([a.GetNumRadicalElectrons() * a.GetAtomicNum() for a in unsanitizedInchiMol.GetAtoms() if a.GetNumRadicalElectrons() != 0]): reasonable += 1 continue diff += 1 print green + 'Empty mol for PubChem Compound ' + \ cid + '\n' + reset continue if x != y: # if there was warning in the first place, then this is # tolerable try: MolToInchi(m, treatWarningAsError=True) MolFromInchi(x, treatWarningAsError=True) except InchiReadWriteError as inst: reasonable += 1 continue # or if there are big rings SanitizeMol(m) if filter(lambda i: i >= 8, [len(r) for r in m.GetRingInfo().AtomRings()]): reasonable += 1 continue # or if RDKit loses bond stereo s = MolToSmiles(m, True) if MolToSmiles(MolFromSmiles(s), True) != s: reasonable += 1 continue # or if it is RDKit SMILES writer unhappy about the mol inchiMol = MolFromInchi(x) rdDepictor.Compute2DCoords(inchiMol) z = MolToInchi(MolFromMolBlock(MolToMolBlock(inchiMol))) if x == z: reasonable += 1 continue diff += 1 print green + 'Molecule mismatch for PubChem Compound ' + \ cid + '\n' + reset + \ inchiDiff(x, y) + reset print else: same += 1 print green + "InChI Read Summary: %d identical, %d variance, %d reasonable variance" % (same, diff, reasonable) + reset self.assertEqual(same, 545) self.assertEqual(diff, 1) self.assertEqual(reasonable, 635) def test2InchiOptions(self): m = MolFromSmiles("CC=C(N)C") inchi1 = MolToInchi(m).split('/', 1)[1] inchi2 = MolToInchi(m, "/SUU").split('/', 1)[1] self.assertEqual(inchi1 + '/b4-3?', inchi2) def test3InchiKey(self): inchi = 'InChI=1S/C9H12/c1-2-6-9-7-4-3-5-8-9/h3-5,7-8H,2,6H2,1H3' self.assertEqual(InchiToInchiKey(inchi), 'ODLMAHJVESYWTB-UHFFFAOYSA-N') if __name__ == '__main__': # only run the test if InChI is available if inchi.INCHI_AVAILABLE: unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/UnitTestInchi.py", "copies": "1", "size": "12348", "license": "bsd-3-clause", "hash": -311306125895810000, "line_mean": 38.3248407643, "line_max": 170, "alpha_frac": 0.5097991578, "autogenerated": false, "ratio": 3.727135526712949, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9699711599594056, "avg_score": 0.007444616983778669, "num_lines": 314 }
INCHI_AVAILABLE = True import logging from rdkit.Chem import rdinchi from rdkit import RDLogger logger = RDLogger.logger() logLevelToLogFunctionLookup = { logging.INFO : logger.info, logging.DEBUG : logger.debug, logging.WARNING : logger.warning, logging.CRITICAL : logger.critical, logging.ERROR : logger.error } class InchiReadWriteError(Exception): pass def MolFromInchi(inchi, sanitize=True, removeHs=True, logLevel=None, treatWarningAsError=False): """Construct a molecule from a InChI string Keyword arguments: sanitize -- set to True to enable sanitization of the molecule. Default is True removeHs -- set to True to remove Hydrogens from a molecule. This only makes sense when sanitization is enabled logLevel -- the log level used for logging logs and messages from InChI API. set to None to diable the logging completely treatWarningAsError -- set to True to raise an exception in case of a molecule that generates warning in calling InChI API. The resultant molecule and error message are part of the excpetion Returns: a rdkit.Chem.rdchem.Mol instance """ try: mol, retcode, message, log = rdinchi.InchiToMol(inchi, sanitize, removeHs) except ValueError as e : logger.error(str(e)) return None if logLevel is not None: if logLevel not in logLevelToLogFunctionLookup: raise ValueError("Unsupported log level: %d" % logLevel) log = logLevelToLogFunctionLookup[logLevel] if retcode == 0: log(message) if retcode != 0: if retcode == 1: logger.warning(message) else: logger.error(message) if treatWarningAsError and retcode != 0: raise InchiReadWriteError(mol, message) return mol def MolToInchiAndAuxInfo(mol, options="", logLevel=None, treatWarningAsError=False): """Returns the standard InChI string and InChI auxInfo for a molecule Keyword arguments: logLevel -- the log level used for logging logs and messages from InChI API. set to None to diable the logging completely treatWarningAsError -- set to True to raise an exception in case of a molecule that generates warning in calling InChI API. The resultant InChI string and AuxInfo string as well as the error message are encoded in the exception. Returns: a tuple of the standard InChI string and the auxInfo string returned by InChI API, in that order, for the input molecule """ inchi, retcode, message, logs, aux = rdinchi.MolToInchi(mol, options) if logLevel is not None: if logLevel not in logLevelToLogFunctionLookup: raise ValueError("Unsupported log level: %d" % logLevel) log = logLevelToLogFunctionLookup[logLevel] if retcode == 0: log(message) if retcode != 0: if retcode == 1: logger.warning(message) else: logger.error(message) if treatWarningAsError and retcode != 0: raise InchiReadWriteError(inchi, aux, message) return inchi, aux def MolToInchi(mol, options="", logLevel=None, treatWarningAsError=False): """Returns the standard InChI string for a molecule Keyword arguments: logLevel -- the log level used for logging logs and messages from InChI API. set to None to diable the logging completely treatWarningAsError -- set to True to raise an exception in case of a molecule that generates warning in calling InChI API. The resultant InChI string and AuxInfo string as well as the error message are encoded in the exception. Returns: the standard InChI string returned by InChI API for the input molecule """ if options.find('AuxNone')==-1: if options: options += " /AuxNone" else: options += "/AuxNone" try: inchi, aux = MolToInchiAndAuxInfo(mol, options, logLevel=logLevel, treatWarningAsError=treatWarningAsError) except InchiReadWriteError as inst: inchi, aux, message = inst.args raise InchiReadWriteError(inchi, message) return inchi def InchiToInchiKey(inchi): """Return the InChI key for the given InChI string. Return None on error""" ret = rdinchi.InchiToInchiKey(inchi) if ret: return ret else: return None __all__ = ['MolToInchiAndAuxInfo', 'MolToInchi', 'MolFromInchi', 'InchiReadWriteError', 'InchiToInchiKey', 'INCHI_AVAILABLE']
{ "repo_name": "adalke/rdkit", "path": "External/INCHI-API/python/inchi.py", "copies": "4", "size": "6215", "license": "bsd-3-clause", "hash": 1759046653580249600, "line_mean": 37.84375, "line_max": 86, "alpha_frac": 0.7029766693, "autogenerated": false, "ratio": 4.0647482014388485, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00838958388330562, "num_lines": 160 }
INCHI_AVAILABLE = True import logging from rdkit.Chem import rdinchi from rdkit import RDLogger logger = RDLogger.logger() logLevelToLogFunctionLookup = { logging.INFO: logger.info, logging.DEBUG: logger.debug, logging.WARNING: logger.warning, logging.CRITICAL: logger.critical, logging.ERROR: logger.error } class InchiReadWriteError(Exception): pass def MolFromInchi(inchi, sanitize=True, removeHs=True, logLevel=None, treatWarningAsError=False): """Construct a molecule from a InChI string Keyword arguments: sanitize -- set to True to enable sanitization of the molecule. Default is True removeHs -- set to True to remove Hydrogens from a molecule. This only makes sense when sanitization is enabled logLevel -- the log level used for logging logs and messages from InChI API. set to None to diable the logging completely treatWarningAsError -- set to True to raise an exception in case of a molecule that generates warning in calling InChI API. The resultant molecule and error message are part of the excpetion Returns: a rdkit.Chem.rdchem.Mol instance """ try: mol, retcode, message, log = rdinchi.InchiToMol(inchi, sanitize, removeHs) except ValueError as e: logger.error(str(e)) return None if logLevel is not None: if logLevel not in logLevelToLogFunctionLookup: raise ValueError("Unsupported log level: %d" % logLevel) log = logLevelToLogFunctionLookup[logLevel] if retcode == 0: log(message) if retcode != 0: if retcode == 1: logger.warning(message) else: logger.error(message) if treatWarningAsError and retcode != 0: raise InchiReadWriteError(mol, message) return mol def MolToInchiAndAuxInfo(mol, options="", logLevel=None, treatWarningAsError=False): """Returns the standard InChI string and InChI auxInfo for a molecule Keyword arguments: logLevel -- the log level used for logging logs and messages from InChI API. set to None to diable the logging completely treatWarningAsError -- set to True to raise an exception in case of a molecule that generates warning in calling InChI API. The resultant InChI string and AuxInfo string as well as the error message are encoded in the exception. Returns: a tuple of the standard InChI string and the auxInfo string returned by InChI API, in that order, for the input molecule """ inchi, retcode, message, logs, aux = rdinchi.MolToInchi(mol, options) if logLevel is not None: if logLevel not in logLevelToLogFunctionLookup: raise ValueError("Unsupported log level: %d" % logLevel) log = logLevelToLogFunctionLookup[logLevel] if retcode == 0: log(message) if retcode != 0: if retcode == 1: logger.warning(message) else: logger.error(message) if treatWarningAsError and retcode != 0: raise InchiReadWriteError(inchi, aux, message) return inchi, aux def MolToInchi(mol, options="", logLevel=None, treatWarningAsError=False): """Returns the standard InChI string for a molecule Keyword arguments: logLevel -- the log level used for logging logs and messages from InChI API. set to None to diable the logging completely treatWarningAsError -- set to True to raise an exception in case of a molecule that generates warning in calling InChI API. The resultant InChI string and AuxInfo string as well as the error message are encoded in the exception. Returns: the standard InChI string returned by InChI API for the input molecule """ if options.find('AuxNone') == -1: if options: options += " /AuxNone" else: options += "/AuxNone" try: inchi, aux = MolToInchiAndAuxInfo(mol, options, logLevel=logLevel, treatWarningAsError=treatWarningAsError) except InchiReadWriteError as inst: inchi, aux, message = inst.args raise InchiReadWriteError(inchi, message) return inchi def InchiToInchiKey(inchi): """Return the InChI key for the given InChI string. Return None on error""" ret = rdinchi.InchiToInchiKey(inchi) if ret: return ret else: return None __all__ = ['MolToInchiAndAuxInfo', 'MolToInchi', 'MolFromInchi', 'InchiReadWriteError', 'InchiToInchiKey', 'INCHI_AVAILABLE']
{ "repo_name": "jandom/rdkit", "path": "External/INCHI-API/python/inchi.py", "copies": "2", "size": "6003", "license": "bsd-3-clause", "hash": -3307375311315942400, "line_mean": 35.1626506024, "line_max": 96, "alpha_frac": 0.7278027653, "autogenerated": false, "ratio": 3.928664921465969, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.014002881617430019, "num_lines": 166 }
INCHI_AVAILABLE = True import rdinchi import logging from rdkit import RDLogger logger = RDLogger.logger() logLevelToLogFunctionLookup = { logging.INFO : logger.info, logging.DEBUG : logger.debug, logging.WARNING : logger.warning, logging.CRITICAL : logger.critical, logging.ERROR : logger.error } class InchiReadWriteError(Exception): pass def MolFromInchi(inchi, sanitize=True, removeHs=True, logLevel=None, treatWarningAsError=False): """Construct a molecule from a InChI string Keyword arguments: sanitize -- set to True to enable sanitization of the molecule. Default is True removeHs -- set to True to remove Hydrogens from a molecule. This only makes sense when sanitization is enabled logLevel -- the log level used for logging logs and messages from InChI API. set to None to diable the logging completely treatWarningAsError -- set to True to raise an exception in case of a molecule that generates warning in calling InChI API. The resultant molecule and error message are part of the excpetion Returns: a rdkit.Chem.rdchem.Mol instance """ try: mol, retcode, message, log = rdinchi.InchiToMol(inchi, sanitize, removeHs) except ValueError,e : logger.error(str(e)) return None if logLevel is not None: if logLogLevel not in logLevelToLogFunctionLookup: raise ValueError("Unsupported log level: %d" % logLogLevel) log = logLevelToLogFunctionLookup[logLevel] if retcode == 0: log(message) if retcode != 0: if retcode == 1: logger.warning(message) else: logger.error(message) if treatWarningAsError and retcode != 0: raise InchiReadWriteError(mol, message) return mol def MolToInchiAndAuxInfo(mol, options="", logLevel=None, treatWarningAsError=False): """Returns the standard InChI string and InChI auxInfo for a molecule Keyword arguments: logLevel -- the log level used for logging logs and messages from InChI API. set to None to diable the logging completely treatWarningAsError -- set to True to raise an exception in case of a molecule that generates warning in calling InChI API. The resultant InChI string and AuxInfo string as well as the error message are encoded in the exception. Returns: a tuple of the standard InChI string and the auxInfo string returned by InChI API, in that order, for the input molecule """ inchi, retcode, message, logs, aux = rdinchi.MolToInchi(mol, options) if logLevel is not None: if logLevel not in logLevelToLogFunctionLookup: raise ValueError("Unsupported log level: %d" % logLevel) log = logLevelToLogFunctionLookup[logLevel] if retcode == 0: log(message) if retcode != 0: if retcode == 1: logger.warning(message) else: logger.error(message) if treatWarningAsError and retcode != 0: raise InchiReadWriteError(inchi, aux, message) return inchi, aux def MolToInchi(mol, options="", logLevel=None, treatWarningAsError=False): """Returns the standard InChI string for a molecule Keyword arguments: logLevel -- the log level used for logging logs and messages from InChI API. set to None to diable the logging completely treatWarningAsError -- set to True to raise an exception in case of a molecule that generates warning in calling InChI API. The resultant InChI string and AuxInfo string as well as the error message are encoded in the exception. Returns: the standard InChI string returned by InChI API for the input molecule """ try: inchi, aux = MolToInchiAndAuxInfo(mol, options, logLevel=logLevel, treatWarningAsError=treatWarningAsError) except InchiReadWriteError,inst: inchi, aux, message = inst raise InchiReadWriteError(inchi, message) return inchi def InchiToInchiKey(inchi): """Return the InChI key for the given InChI string. Return None on error""" ret = rdinchi.InchiToInchiKey(inchi) if ret: return ret else: return None __all__ = ['MolToInchiAndAuxInfo', 'MolToInchi', 'MolFromInchi', 'InchiReadWriteError', 'InchiToInchiKey', 'INCHI_AVAILABLE']
{ "repo_name": "rdkit/rdkit-orig", "path": "External/INCHI-API/python/inchi.py", "copies": "1", "size": "6047", "license": "bsd-3-clause", "hash": 7215080172492339000, "line_mean": 38.522875817, "line_max": 86, "alpha_frac": 0.7097734414, "autogenerated": false, "ratio": 4.069313593539704, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5279087034939703, "avg_score": null, "num_lines": null }
from rdkit import Chem from rdkit import RDConfig from rdkit import DataStructs from rdkit.Chem import rdMolDescriptors as rdMD from rdkit.Chem import rdmolops from rdkit.Chem import Draw from rdkit.six import iteritems import numpy import math import copy from matplotlib import cm def GetAtomicWeightsForFingerprint(refMol, probeMol, fpFunction, metric=DataStructs.DiceSimilarity): """ Calculates the atomic weights for the probe molecule based on a fingerprint function and a metric. Parameters: refMol -- the reference molecule probeMol -- the probe molecule fpFunction -- the fingerprint function metric -- the similarity metric Note: If fpFunction needs additional parameters, use a lambda construct """ if hasattr(probeMol, '_fpInfo'): delattr(probeMol, '_fpInfo') if hasattr(refMol, '_fpInfo'): delattr(refMol, '_fpInfo') refFP = fpFunction(refMol, -1) probeFP = fpFunction(probeMol, -1) baseSimilarity = metric(refFP, probeFP) # loop over atoms weights = [] for atomId in range(probeMol.GetNumAtoms()): newFP = fpFunction(probeMol, atomId) newSimilarity = metric(refFP, newFP) weights.append(baseSimilarity - newSimilarity) if hasattr(probeMol, '_fpInfo'): delattr(probeMol, '_fpInfo') if hasattr(refMol, '_fpInfo'): delattr(refMol, '_fpInfo') return weights def GetAtomicWeightsForModel(probeMol, fpFunction, predictionFunction): """ Calculates the atomic weights for the probe molecule based on a fingerprint function and the prediction function of a ML model. Parameters: probeMol -- the probe molecule fpFunction -- the fingerprint function predictionFunction -- the prediction function of the ML model """ if hasattr(probeMol, '_fpInfo'): delattr(probeMol, '_fpInfo') probeFP = fpFunction(probeMol, -1) baseProba = predictionFunction(probeFP) # loop over atoms weights = [] for atomId in range(probeMol.GetNumAtoms()): newFP = fpFunction(probeMol, atomId) newProba = predictionFunction(newFP) weights.append(baseProba - newProba) if hasattr(probeMol, '_fpInfo'): delattr(probeMol, '_fpInfo') return weights def GetStandardizedWeights(weights): """ Normalizes the weights, such that the absolute maximum weight equals 1.0. Parameters: weights -- the list with the atomic weights """ tmp = [math.fabs(w) for w in weights] currentMax = max(tmp) if currentMax > 0: return [w/currentMax for w in weights], currentMax else: return weights, currentMax def GetSimilarityMapFromWeights(mol, weights, colorMap=cm.PiYG, scale=-1, size=(250, 250), sigma=None, #@UndefinedVariable #pylint: disable=E1101 coordScale=1.5, step=0.01, colors='k', contourLines=10, alpha=0.5, **kwargs): """ Generates the similarity map for a molecule given the atomic weights. Parameters: mol -- the molecule of interest colorMap -- the matplotlib color map scheme scale -- the scaling: scale < 0 -> the absolute maximum weight is used as maximum scale scale = double -> this is the maximum scale size -- the size of the figure sigma -- the sigma for the Gaussians coordScale -- scaling factor for the coordinates step -- the step for calcAtomGaussian colors -- color of the contour lines contourLines -- if integer number N: N contour lines are drawn if list(numbers): contour lines at these numbers are drawn alpha -- the alpha blending value for the contour lines kwargs -- additional arguments for drawing """ if mol.GetNumAtoms() < 2: raise ValueError("too few atoms") fig = Draw.MolToMPL(mol, coordScale=coordScale, size=size, **kwargs) if sigma is None: if mol.GetNumBonds() > 0: bond = mol.GetBondWithIdx(0) idx1 = bond.GetBeginAtomIdx() idx2 = bond.GetEndAtomIdx() sigma = 0.3 * math.sqrt(sum([(mol._atomPs[idx1][i]-mol._atomPs[idx2][i])**2 for i in range(2)])) else: sigma = 0.3 * math.sqrt(sum([(mol._atomPs[0][i]-mol._atomPs[1][i])**2 for i in range(2)])) sigma = round(sigma, 2) x, y, z = Draw.calcAtomGaussians(mol, sigma, weights=weights, step=step) # scaling if scale <= 0.0: maxScale = max(math.fabs(numpy.min(z)), math.fabs(numpy.max(z))) else: maxScale = scale # coloring fig.axes[0].imshow(z, cmap=colorMap, interpolation='bilinear', origin='lower', extent=(0,1,0,1), vmin=-maxScale, vmax=maxScale) # contour lines # only draw them when at least one weight is not zero if len([w for w in weights if w != 0.0]): fig.axes[0].contour(x, y, z, contourLines, colors=colors, alpha=alpha, **kwargs) return fig def GetSimilarityMapForFingerprint(refMol, probeMol, fpFunction, metric=DataStructs.DiceSimilarity, **kwargs): """ Generates the similarity map for a given reference and probe molecule, fingerprint function and similarity metric. Parameters: refMol -- the reference molecule probeMol -- the probe molecule fpFunction -- the fingerprint function metric -- the similarity metric. kwargs -- additional arguments for drawing """ weights = GetAtomicWeightsForFingerprint(refMol, probeMol, fpFunction, metric) weights, maxWeight = GetStandardizedWeights(weights) fig = GetSimilarityMapFromWeights(probeMol, weights, **kwargs) return fig, maxWeight def GetSimilarityMapForModel(probeMol, fpFunction, predictionFunction, **kwargs): """ Generates the similarity map for a given ML model and probe molecule, and fingerprint function. Parameters: probeMol -- the probe molecule fpFunction -- the fingerprint function predictionFunction -- the prediction function of the ML model kwargs -- additional arguments for drawing """ weights = GetAtomicWeightsForModel(probeMol, fpFunction, predictionFunction) weights, maxWeight = GetStandardizedWeights(weights) fig = GetSimilarityMapFromWeights(probeMol, weights, **kwargs) return fig, maxWeight apDict = {} apDict['normal'] = lambda m, bits, minl, maxl, bpe, ia: rdMD.GetAtomPairFingerprint(m, minLength=minl, maxLength=maxl, ignoreAtoms=ia) apDict['hashed'] = lambda m, bits, minl, maxl, bpe, ia: rdMD.GetHashedAtomPairFingerprint(m, nBits=bits, minLength=minl, maxLength=maxl, ignoreAtoms=ia) apDict['bv'] = lambda m, bits, minl, maxl, bpe, ia: rdMD.GetHashedAtomPairFingerprintAsBitVect(m, nBits=bits, minLength=minl, maxLength=maxl, nBitsPerEntry=bpe, ignoreAtoms=ia) # usage: lambda m,i: GetAPFingerprint(m, i, fpType, nBits, minLength, maxLength, nBitsPerEntry) def GetAPFingerprint(mol, atomId=-1, fpType='normal', nBits=2048, minLength=1, maxLength=30, nBitsPerEntry=4): """ Calculates the atom pairs fingerprint with the torsions of atomId removed. Parameters: mol -- the molecule of interest atomId -- the atom to remove the pairs for (if -1, no pair is removed) fpType -- the type of AP fingerprint ('normal', 'hashed', 'bv') nBits -- the size of the bit vector (only for fpType='bv') minLength -- the minimum path length for an atom pair maxLength -- the maxmimum path length for an atom pair nBitsPerEntry -- the number of bits available for each pair """ if fpType not in ['normal', 'hashed', 'bv']: raise ValueError("Unknown Atom pairs fingerprint type") if atomId < 0: return apDict[fpType](mol, nBits, minLength, maxLength, nBitsPerEntry, 0) if atomId >= mol.GetNumAtoms(): raise ValueError("atom index greater than number of atoms") return apDict[fpType](mol, nBits, minLength, maxLength, nBitsPerEntry, [atomId]) ttDict = {} ttDict['normal'] = lambda m, bits, ts, bpe, ia: rdMD.GetTopologicalTorsionFingerprint(m, targetSize=ts, ignoreAtoms=ia) ttDict['hashed'] = lambda m, bits, ts, bpe, ia: rdMD.GetHashedTopologicalTorsionFingerprint(m, nBits=bits, targetSize=ts, ignoreAtoms=ia) ttDict['bv'] = lambda m, bits, ts, bpe, ia: rdMD.GetHashedTopologicalTorsionFingerprintAsBitVect(m, nBits=bits, targetSize=ts, nBitsPerEntry=bpe, ignoreAtoms=ia) # usage: lambda m,i: GetTTFingerprint(m, i, fpType, nBits, targetSize) def GetTTFingerprint(mol, atomId=-1, fpType='normal', nBits=2048, targetSize=4, nBitsPerEntry=4): """ Calculates the topological torsion fingerprint with the pairs of atomId removed. Parameters: mol -- the molecule of interest atomId -- the atom to remove the torsions for (if -1, no torsion is removed) fpType -- the type of TT fingerprint ('normal', 'hashed', 'bv') nBits -- the size of the bit vector (only for fpType='bv') minLength -- the minimum path length for an atom pair maxLength -- the maxmimum path length for an atom pair nBitsPerEntry -- the number of bits available for each torsion """ if fpType not in ['normal', 'hashed', 'bv']: raise ValueError("Unknown Topological torsion fingerprint type") if atomId < 0: return ttDict[fpType](mol, nBits, targetSize, nBitsPerEntry, 0) if atomId >= mol.GetNumAtoms(): raise ValueError("atom index greater than number of atoms") return ttDict[fpType](mol, nBits, targetSize, nBitsPerEntry, [atomId]) # usage: lambda m,i: GetMorganFingerprint(m, i, radius, fpType, nBits, useFeatures) def GetMorganFingerprint(mol, atomId=-1, radius=2, fpType='bv', nBits=2048, useFeatures=False): """ Calculates the Morgan fingerprint with the environments of atomId removed. Parameters: mol -- the molecule of interest radius -- the maximum radius fpType -- the type of Morgan fingerprint: 'count' or 'bv' atomId -- the atom to remove the environments for (if -1, no environments is removed) nBits -- the size of the bit vector (only for fpType = 'bv') useFeatures -- if false: ConnectivityMorgan, if true: FeatureMorgan """ if fpType not in ['bv', 'count']: raise ValueError("Unknown Morgan fingerprint type") if not hasattr(mol, '_fpInfo'): info = {} # get the fingerprint if fpType == 'bv': molFp = rdMD.GetMorganFingerprintAsBitVect(mol, radius, nBits=nBits, useFeatures=useFeatures, bitInfo=info) else: molFp = rdMD.GetMorganFingerprint(mol, radius, useFeatures=useFeatures, bitInfo=info) # construct the bit map if fpType == 'bv': bitmap = [DataStructs.ExplicitBitVect(nBits) for x in range(mol.GetNumAtoms())] else: bitmap = [[] for x in range(mol.GetNumAtoms())] for bit, es in iteritems(info): for at1, rad in es: if rad == 0: # for radius 0 if fpType == 'bv': bitmap[at1][bit] = 1 else: bitmap[at1].append(bit) else: # for radii > 0 env = Chem.FindAtomEnvironmentOfRadiusN(mol, rad, at1) amap = {} submol = Chem.PathToSubmol(mol, env, atomMap=amap) for at2 in amap.keys(): if fpType == 'bv': bitmap[at2][bit] = 1 else: bitmap[at2].append(bit) mol._fpInfo = (molFp, bitmap) if atomId < 0: return mol._fpInfo[0] else: # remove the bits of atomId if atomId >= mol.GetNumAtoms(): raise ValueError("atom index greater than number of atoms") if len(mol._fpInfo) != 2: raise ValueError("_fpInfo not set") if fpType == 'bv': molFp = mol._fpInfo[0] ^ mol._fpInfo[1][atomId] # xor else: # count molFp = copy.deepcopy(mol._fpInfo[0]) # delete the bits with atomId for bit in mol._fpInfo[1][atomId]: molFp[bit] -= 1 return molFp # usage: lambda m,i: GetRDKFingerprint(m, i, fpType, nBits, minPath, maxPath, nBitsPerHash) def GetRDKFingerprint(mol, atomId=-1, fpType='bv', nBits=2048, minPath=1, maxPath=5, nBitsPerHash=2): """ Calculates the RDKit fingerprint with the paths of atomId removed. Parameters: mol -- the molecule of interest atomId -- the atom to remove the paths for (if -1, no path is removed) fpType -- the type of RDKit fingerprint: 'bv' nBits -- the size of the bit vector minPath -- minimum path length maxPath -- maximum path length nBitsPerHash -- number of to set per path """ if fpType not in ['bv', '']: raise ValueError("Unknown RDKit fingerprint type") fpType = 'bv' if not hasattr(mol, '_fpInfo'): info = [] # list with bits for each atom # get the fingerprint molFp = Chem.RDKFingerprint(mol, fpSize=nBits, minPath=minPath, maxPath=maxPath, nBitsPerHash=nBitsPerHash, atomBits=info) mol._fpInfo = (molFp, info) if atomId < 0: return mol._fpInfo[0] else: # remove the bits of atomId if atomId >= mol.GetNumAtoms(): raise ValueError("atom index greater than number of atoms") if len(mol._fpInfo) != 2: raise ValueError("_fpInfo not set") molFp = copy.deepcopy(mol._fpInfo[0]) molFp.UnSetBitsFromList(mol._fpInfo[1][atomId]) return molFp
{ "repo_name": "strets123/rdkit", "path": "rdkit/Chem/Draw/SimilarityMaps.py", "copies": "3", "size": "14368", "license": "bsd-3-clause", "hash": 486695371031217800, "line_mean": 42.9388379205, "line_max": 176, "alpha_frac": 0.7088669265, "autogenerated": false, "ratio": 3.567030784508441, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.018682289202233093, "num_lines": 327 }
""" unit testing code for molecule drawing """ from rdkit import RDConfig import unittest,os,tempfile from rdkit import Chem from rdkit.Chem import Draw try: from rdkit.Chem.Draw import SimilarityMaps as sm except ImportError: sm = None from rdkit.RDLogger import logger logger = logger() class TestCase(unittest.TestCase): def setUp(self): self.mol1 = Chem.MolFromSmiles('c1ccccc1') self.mol2 = Chem.MolFromSmiles('c1ccncc1') def testSimilarityMap(self): # Morgan2 BV refWeights = [0.5, 0.5, 0.5, -0.5, 0.5, 0.5] weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetMorganFingerprint(m, i, radius=2, fpType='bv')) for w,r in zip(weights, refWeights): self.assertEqual(w, r) fig, maxWeight = sm.GetSimilarityMapForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetMorganFingerprint(m, i, radius=2, fpType='bv')) self.assertEqual(maxWeight, 0.5) weights, maxWeight = sm.GetStandardizedWeights(weights) self.assertEqual(maxWeight, 0.5) refWeights = [1.0, 1.0, 1.0, -1.0, 1.0, 1.0] for w,r in zip(weights, refWeights): self.assertEqual(w, r) weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetMorganFingerprint(m, i, fpType='count')) self.assertTrue(weights[3] < 0) weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetMorganFingerprint(m, i, fpType='bv', useFeatures=True)) self.assertTrue(weights[3] < 0) # hashed AP BV refWeights = [0.09523, 0.17366, 0.17366, -0.23809, 0.17366, 0.17366] weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetAPFingerprint(m, i, fpType='bv', nBits=1024)) for w,r in zip(weights, refWeights): self.assertAlmostEqual(w, r, 4) weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetAPFingerprint(m, i, fpType='normal')) self.assertTrue(weights[3] < 0) weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetAPFingerprint(m, i, fpType='hashed')) self.assertTrue(weights[3] < 0) # hashed TT BV refWeights = [0.5, 0.5, -0.16666, -0.5, -0.16666, 0.5] weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetTTFingerprint(m, i, fpType='bv', nBits=1024, nBitsPerEntry=1)) for w,r in zip(weights, refWeights): self.assertAlmostEqual(w, r, 4) weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetTTFingerprint(m, i, fpType='normal')) self.assertTrue(weights[3] < 0) weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetTTFingerprint(m, i, fpType='hashed')) self.assertTrue(weights[3] < 0) # RDK fingerprint BV refWeights = [0.42105, 0.42105, 0.42105, -0.32895, 0.42105, 0.42105] weights = sm.GetAtomicWeightsForFingerprint(self.mol1, self.mol2, lambda m, i: sm.GetRDKFingerprint(m, i, nBits=1024, nBitsPerHash=1)) for w,r in zip(weights, refWeights): self.assertAlmostEqual(w, r, 4) if __name__ == '__main__': try: import matplotlib from rdkit.Chem.Draw.mplCanvas import Canvas except ImportError: pass except RuntimeError: # happens with GTK can't initialize pass else: unittest.main()
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/Draw/UnitTestSimilarityMaps.py", "copies": "3", "size": "5002", "license": "bsd-3-clause", "hash": 6999963807681221000, "line_mean": 45.7476635514, "line_max": 151, "alpha_frac": 0.7229108357, "autogenerated": false, "ratio": 3.3302263648468706, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.555313720054687, "avg_score": null, "num_lines": null }
""" unit testing code for the Scoring functionality """ from rdkit import RDConfig import unittest, os from rdkit.ML.Scoring import Scoring import math class TestCase(unittest.TestCase): def setUp(self): # generate a scored list of 400 molecules with 20 actives self.numActives = 20 self.numDecoys = 380 self.numMol = self.numActives + self.numDecoys act = [[1] for x in range(0,self.numActives)] dcy = [[0] for x in range(0,self.numDecoys)] self.scoreBestCase = act + dcy self.scoreWorstCase = dcy + act self.scoreEmptyList = [] self.scoreAllActives = [[1] for x in range(0,self.numMol)] self.scoreAllDecoys = [[0] for x in range(0,self.numMol)] self.index = 0 # where the active/inactive information lies # test the 5% fraction self.fractions = [float(self.numActives)/self.numMol] self.fracSmall = [self.fractions[0]/100] # exponential weight self.alpha = 100.0 # accuracy for float number comparison self.acc = 4 def test1(self): """ test enrichment factor """ # best case enrich = Scoring.CalcEnrichment(self.scoreBestCase, self.index, self.fractions) self.assertAlmostEqual(enrich[0], float(self.numActives), self.acc) # worst case enrich = Scoring.CalcEnrichment(self.scoreWorstCase, self.index, self.fractions) self.assertAlmostEqual(enrich[0], 0.0, self.acc) # empty list self.assertRaises(ValueError, Scoring.CalcEnrichment, self.scoreEmptyList, self.index, self.fractions) # all actives enrich = Scoring.CalcEnrichment(self.scoreAllActives, self.index, self.fractions) self.assertAlmostEqual(enrich[0], 1.0, self.acc) # all decoys enrich = Scoring.CalcEnrichment(self.scoreAllDecoys, self.index, self.fractions) self.assertEqual(enrich[0], 0.0) # fraction * numMol is smaller than 1 enrich = Scoring.CalcEnrichment(self.scoreBestCase, self.index, self.fracSmall) self.assertAlmostEqual(enrich[0], float(self.numActives), self.acc) # fraction list is empty self.assertRaises(ValueError, Scoring.CalcEnrichment, self.scoreBestCase, self.index, []) # fraction == 0.0 enrich = Scoring.CalcEnrichment(self.scoreBestCase, self.index, [0.0]) self.assertAlmostEqual(enrich[0], float(self.numActives), self.acc) # fraction < 0 self.assertRaises(ValueError, Scoring.CalcEnrichment, self.scoreBestCase, self.index, [-0.05]) # fraction > 1 self.assertRaises(ValueError, Scoring.CalcEnrichment, self.scoreBestCase, self.index, [1.5]) def test2(self): """ test RIE """ ratio = float(self.numActives) / self.numMol # best case RIEmax = ((1 - math.exp(-self.alpha*ratio)) / (1 - math.exp(-self.alpha))) / ratio rie = Scoring.CalcRIE(self.scoreBestCase, self.index, self.alpha) self.assertAlmostEqual(rie, RIEmax, self.acc) # worst case RIEmin = ((1 - math.exp(self.alpha*ratio)) / (1 - math.exp(self.alpha))) / ratio rie = Scoring.CalcRIE(self.scoreWorstCase, self.index, self.alpha) self.assertAlmostEqual(rie, RIEmin, self.acc) # empty list self.assertRaises(ValueError, Scoring.CalcRIE, self.scoreEmptyList, self.index, self.alpha) # alpha == 0 self.assertRaises(ValueError, Scoring.CalcRIE, self.scoreBestCase, self.index, 0.0) # all decoys rie = Scoring.CalcRIE(self.scoreAllDecoys, self.index, self.alpha) self.assertEqual(rie, 0.0) def test3(self): """ test area under the curve (AUC) of ROC """ # best case auc = Scoring.CalcAUC(self.scoreBestCase, self.index) self.assertAlmostEqual(auc, 1.0, self.acc) # worst case auc = Scoring.CalcAUC(self.scoreWorstCase, self.index) self.assertAlmostEqual(auc, 0.0, self.acc) # empty list self.assertRaises(ValueError, Scoring.CalcAUC, self.scoreEmptyList, self.index) # all actives auc = Scoring.CalcAUC(self.scoreAllActives, self.index) self.assertAlmostEqual(auc, 0.0, self.acc) # all decoys auc = Scoring.CalcAUC(self.scoreAllDecoys, self.index) self.assertAlmostEqual(auc, 0.0, self.acc) def test4(self): """ test BEDROC """ # best case bedroc = Scoring.CalcBEDROC(self.scoreBestCase, self.index, self.alpha) self.assertAlmostEqual(bedroc, 1.0, self.acc) # worst case bedroc = Scoring.CalcBEDROC(self.scoreWorstCase, self.index, self.alpha) self.assertAlmostEqual(bedroc, 0.0, self.acc) # empty list self.assertRaises(ValueError, Scoring.CalcBEDROC, self.scoreEmptyList, self.index, self.alpha) # alpha == 0.0 self.assertRaises(ValueError, Scoring.CalcBEDROC, self.scoreBestCase, self.index, 0.0) # all actives bedroc = Scoring.CalcBEDROC(self.scoreAllActives, self.index, self.alpha) self.assertEqual(bedroc, 1.0) # all decoys bedroc = Scoring.CalcBEDROC(self.scoreAllDecoys, self.index, self.alpha) self.assertEqual(bedroc, 0.0) if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/ML/Scoring/UnitTestScoring.py", "copies": "6", "size": "6977", "license": "bsd-3-clause", "hash": -6167655778724043000, "line_mean": 45.5133333333, "line_max": 110, "alpha_frac": 0.6760785438, "autogenerated": false, "ratio": 3.588991769547325, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7265070313347326, "avg_score": null, "num_lines": null }
from rdkit.Chem.Draw.canvasbase import CanvasBase from PySide import QtGui, QtCore class Canvas(CanvasBase): def __init__(self, size): self.size = size self.qsize = QtCore.QSize(*size) self.pixmap = QtGui.QPixmap(self.qsize) self.painter = QtGui.QPainter(self.pixmap) self.painter.setRenderHint(QtGui.QPainter.Antialiasing, True) self.painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, True) self.painter.fillRect(0, 0, size[0], size[1], QtCore.Qt.white) def addCanvasLine(self, p1, p2, color=(0, 0, 0), color2=None, **kwargs): if 'dash' in kwargs: line_type = QtCore.Qt.DashLine else: line_type = QtCore.Qt.SolidLine qp1 = QtCore.QPointF(*p1) qp2 = QtCore.QPointF(*p2) qpm = QtCore.QPointF((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) if color2 and color2 != color: rgb = [int(c * 255) for c in color] pen = QtGui.QPen(QtGui.QColor(*rgb), 1, line_type) self.painter.setPen(pen) self.painter.drawLine(qp1, qpm) rgb2 = [int(c * 255) for c in color2] pen.setColor(QtGui.QColor(*rgb2)) self.painter.setPen(pen) self.painter.drawLine(qpm, qp2) else: rgb = [int(c * 255) for c in color] pen = QtGui.QPen(QtGui.QColor(*rgb), 1, line_type) self.painter.setPen(pen) self.painter.drawLine(qp1, qp2) def addCanvasText(self, text, pos, font, color=(0, 0, 0), **kwargs): orientation = kwargs.get('orientation', 'E') qfont = QtGui.QFont("Helvetica", font.size * 1.5) qtext = QtGui.QTextDocument() qtext.setDefaultFont(qfont) colored = [int(c * 255) for c in color] colored.append(text) html_format = "<span style='color:rgb({},{},{})'>{}</span>" formatted = html_format.format(*colored) qtext.setHtml(formatted) if orientation == 'N': qpos = QtCore.QPointF(pos[0] - qtext.idealWidth() / 2, pos[1] - font.size) elif orientation == 'W': qpos = QtCore.QPointF(pos[0] - qtext.idealWidth() + font.size, pos[1] - font.size) else: qpos = QtCore.QPointF(pos[0] - font.size, pos[1] - font.size) self.painter.save() self.painter.translate(qpos) qtext.drawContents(self.painter) self.painter.restore() return font.size * 1.8, font.size * 1.8, 0 def addCanvasPolygon(self, ps, color=(0, 0, 0), fill=True, stroke=False, **kwargs): polygon = QtGui.QPolygonF() for ver in ps: polygon.append(QtCore.QPointF(*ver)) pen = QtGui.QPen(QtGui.QColor(*color), 1, QtCore.Qt.SolidLine) self.painter.setPen(pen) self.painter.setBrush(QtGui.QColor(0, 0, 0)) self.painter.drawPolygon(polygon) def addCanvasDashedWedge(self, p1, p2, p3, dash=(2, 2), color=(0, 0, 0), color2=None, **kwargs): rgb = [int(c * 255) for c in color] pen = QtGui.QPen(QtGui.QColor(*rgb), 1, QtCore.Qt.SolidLine) self.painter.setPen(pen) dash = (4, 4) pts1 = self._getLinePoints(p1, p2, dash) pts2 = self._getLinePoints(p1, p3, dash) if len(pts2) < len(pts1): pts2, pts1 = pts1, pts2 for i in range(len(pts1)): qp1 = QtCore.QPointF(pts1[i][0], pts1[i][1]) qp2 = QtCore.QPointF(pts2[i][0], pts2[i][1]) self.painter.drawLine(qp1, qp2) def flush(self): self.painter.end()
{ "repo_name": "strets123/rdkit", "path": "rdkit/Chem/Draw/qtCanvas.py", "copies": "4", "size": "3963", "license": "bsd-3-clause", "hash": -9172358714070325000, "line_mean": 38.63, "line_max": 78, "alpha_frac": 0.5662376987, "autogenerated": false, "ratio": 3.1303317535545023, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 100 }
# $Id$ # # Created by Greg Landrum, July 2008 # from __future__ import print_function from rdkit import RDConfig import os, sys import unittest from rdkit import DataStructs, Chem from rdkit.Avalon import pyAvalonTools struchk_conf_path = os.path.join(RDConfig.RDDataDir, 'struchk', '') struchk_log_path = '' STRUCHK_INIT = '''-tm -ta %(struchk_conf_path)scheckfgs.trn -tm -or -ca %(struchk_conf_path)scheckfgs.chk -cc -cl 3 -cs -cn 999 -l %(struchk_log_path)sstruchk.log''' % locals() STRUCHK_INIT_IN_MEMORY_LOGGING = '''-tm -ta %(struchk_conf_path)scheckfgs.trn -tm -or -ca %(struchk_conf_path)scheckfgs.chk -cc -cl 3 -cs -cn 999''' % locals() # # PubChem test molecule converted from the RCSB # mondo errors here. atom_clash = """2FV9_002_B_2 RCSB PDB01151502013D Coordinates from PDB:2FV9:B:2 Model:1 without hydrogens 32 32 0 0 0 0 999 V2000 46.8220 28.7360 39.6060 C 0 0 0 0 0 0 0 0 0 0 0 0 47.3620 28.0340 38.3430 C 0 0 0 0 0 0 0 0 0 0 0 0 47.5920 29.0540 37.2270 C 0 0 0 0 0 0 0 0 0 0 0 0 48.4130 28.4900 36.0770 C 0 0 0 0 0 0 0 0 0 0 0 0 47.1640 31.0380 40.1700 C 0 0 0 0 0 0 0 0 0 0 0 0 46.6160 27.6990 40.7140 C 0 0 0 0 0 0 0 0 0 0 0 0 45.0330 26.1340 41.6460 C 0 0 0 0 0 0 0 0 0 0 0 0 44.1100 26.4530 42.8300 C 0 0 0 0 0 0 0 0 0 0 0 0 49.2550 34.1450 39.3140 C 0 0 0 0 0 0 0 0 0 0 0 0 48.2670 33.0140 39.1740 C 0 0 0 0 0 0 0 0 0 0 0 0 44.3710 25.0810 40.7680 C 0 0 0 0 0 0 0 0 0 0 0 0 46.3620 26.9550 37.9090 C 0 0 0 0 0 0 0 0 0 0 0 0 47.7210 29.8260 39.9930 N 0 0 0 0 0 0 0 0 0 0 0 0 47.5720 27.2580 41.3530 O 0 0 0 0 0 0 0 0 0 0 0 0 44.7760 23.9020 40.8430 O 0 0 0 0 0 0 0 0 0 0 0 0 49.7640 36.2780 39.7670 O 0 0 0 0 0 0 0 0 0 0 0 0 44.8290 27.0700 44.0370 C 0 0 0 0 0 0 0 0 0 0 0 0 46.0700 26.2600 44.4160 C 0 0 0 0 0 0 0 0 0 0 0 0 43.8840 27.1450 45.2400 C 0 0 0 0 0 0 0 0 0 0 0 0 48.7580 35.3740 39.5170 N 0 0 0 0 0 0 0 0 0 0 0 0 50.4620 33.9280 39.2410 O 0 0 0 0 0 0 0 0 0 0 0 0 48.1640 32.1600 40.4390 C 0 0 0 0 0 0 0 0 0 0 0 0 47.7340 32.9890 41.6620 C 0 0 0 0 0 0 0 0 0 0 0 0 45.9630 31.2790 40.1090 O 0 0 0 0 0 0 0 0 0 0 0 0 45.3280 27.3570 40.9080 N 0 0 0 0 0 0 0 0 0 0 0 0 43.4500 25.4420 40.0020 O 0 0 0 0 0 0 0 0 0 0 0 0 47.8720 32.1800 42.9370 C 0 0 0 0 0 0 0 0 0 0 0 0 49.0780 32.2360 43.6910 C 0 0 0 0 0 0 0 0 0 0 0 0 49.1970 31.5090 44.9110 C 0 0 0 0 0 0 0 0 0 0 0 0 48.1080 30.7170 45.3760 C 0 0 0 0 0 0 0 0 0 0 0 0 46.9120 30.6330 44.6100 C 0 0 0 0 0 0 0 0 0 0 0 0 46.7920 31.3650 43.3900 C 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 0 0 0 1 6 1 0 0 0 0 1 13 1 0 0 0 0 2 3 1 0 0 0 0 2 12 1 0 0 0 0 3 4 1 0 0 0 0 5 13 1 0 0 0 0 5 22 1 0 0 0 0 5 24 2 0 0 0 0 6 14 2 0 0 0 0 6 25 1 0 0 0 0 7 8 1 0 0 0 0 7 11 1 0 0 0 0 7 25 1 0 0 0 0 8 17 1 0 0 0 0 9 10 1 0 0 0 0 9 20 1 0 0 0 0 9 21 2 0 0 0 0 10 22 1 0 0 0 0 11 15 2 0 0 0 0 11 26 1 0 0 0 0 16 20 1 0 0 0 0 17 18 1 0 0 0 0 17 19 1 0 0 0 0 22 23 1 0 0 0 0 23 27 1 0 0 0 0 27 28 2 0 0 0 0 27 32 1 0 0 0 0 28 29 1 0 0 0 0 29 30 2 0 0 0 0 30 31 1 0 0 0 0 31 32 2 0 0 0 0 M END > <InstanceId> 2FV9_002_B_2 > <ChemCompId> 002 > <PdbId> 2FV9 > <ChainId> B > <ResidueNumber> 2 > <InsertionCode> > <Model> 1 > <AltIds> > <MissingHeavyAtoms> 0 > <ObservedFormula> C23 N3 O6 > <Name> N-[(2R)-2-BENZYL-4-(HYDROXYAMINO)-4-OXOBUTANOYL]-L-ISOLEUCYL-L-LEUCINE > <SystematicName> (2S)-2-[[(2S,3S)-2-[[(2R)-4-(hydroxyamino)-4-oxo-2-(phenylmethyl)butanoyl]amino]-3-methyl-pentanoyl]amino]-4-methyl-pentanoic acid > <Synonyms> > <Type> NON-POLYMER > <Formula> C23 H35 N3 O6 > <MolecularWeight> 449.541 > <ModifiedDate> 2011-06-04 > <Parent> > <OneLetterCode> > <SubcomponentList> > <AmbiguousFlag> > <InChI> InChI=1S/C23H35N3O6/c1-5-15(4)20(22(29)24-18(23(30)31)11-14(2)3)25-21(28)17(13-19(27)26-32)12-16-9-7-6-8-10-16/h6-10,14-15,17-18,20,32H,5,11-13H2,1-4H3,(H,24,29)(H,25,28)(H,26,27)(H,30,31)/t15-,17+,18-,20-/m0/s1 > <InChIKey> MWZOULASPWUGJJ-NFBUACBFSA-N > <SMILES> CC[C@H](C)[C@@H](C(=O)N[C@@H](CC(C)C)C(=O)O)NC(=O)[C@H](Cc1ccccc1)CC(=O)NO $$$$ """ def feq(v1, v2, tol=1e-4): return abs(v1 - v2) < tol class TestCase(unittest.TestCase): def setUp(self): pass def test1(self): m1 = Chem.MolFromSmiles('c1cccnc1') smi = pyAvalonTools.GetCanonSmiles(m1) self.assertTrue(smi == 'c1ccncc1') smi = pyAvalonTools.GetCanonSmiles('c1cccnc1', True) self.assertTrue(smi == 'c1ccncc1') def test2(self): tgts = ['CC1=CC(=O)C=CC1=O', 'c2ccc1SC(=Nc1c2)SSC4=Nc3ccccc3S4', '[O-][N+](=O)c1cc(Cl)c(O)c(c1)[N+]([O-])=O', 'N=C1NC=C(S1)[N+]([O-])=O', 'Nc3ccc2C(=O)c1ccccc1C(=O)c2c3', 'OC(=O)c1ccccc1C3=C2C=CC(=O)C(Br)=C2Oc4c3ccc(O)c4Br', 'CN(C)C2C(=O)c1ccccc1C(=O)C=2Cl', 'Cc3ccc2C(=O)c1ccccc1C(=O)c2c3[N+]([O-])=O', r'C/C(=N\O)/C(/C)=N/O', 'c1ccc(cc1)P(c2ccccc2)c3ccccc3'] with open(os.path.join(RDConfig.RDDataDir, 'NCI', 'first_200.props.sdf'), 'r') as f: d = f.read() mbs = d.split('$$$$\n')[:10] smis = [pyAvalonTools.GetCanonSmiles(mb, False) for mb in mbs] self.assertTrue(smis == tgts) smis = [pyAvalonTools.GetCanonSmiles(smi, True) for smi in smis] self.assertTrue(smis == tgts) def test3(self): bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ccccn1')) self.assertEqual(len(bv), 512) self.assertEqual(bv.GetNumOnBits(), 20) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ccccc1')) self.assertEqual(bv.GetNumOnBits(), 8) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1nnccc1')) self.assertEqual(bv.GetNumOnBits(), 30) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ncncc1')) self.assertEqual(bv.GetNumOnBits(), 27) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ncncc1'), nBits=1024) self.assertEqual(len(bv), 1024) self.assertTrue(bv.GetNumOnBits() > 27) def test4(self): bv = pyAvalonTools.GetAvalonFP('c1ccccn1', True) self.assertEqual(bv.GetNumOnBits(), 20) bv = pyAvalonTools.GetAvalonFP('c1ccccc1', True) self.assertEqual(bv.GetNumOnBits(), 8) bv = pyAvalonTools.GetAvalonFP('c1nnccc1', True) self.assertEqual(bv.GetNumOnBits(), 30) bv = pyAvalonTools.GetAvalonFP('c1ncncc1', True) self.assertEqual(bv.GetNumOnBits(), 27) bv = pyAvalonTools.GetAvalonFP('c1ncncc1', True, nBits=1024) self.assertEqual(len(bv), 1024) self.assertTrue(bv.GetNumOnBits() > 27) bv = pyAvalonTools.GetAvalonFP(Chem.MolToMolBlock(Chem.MolFromSmiles('c1ccccn1')), False) self.assertEqual(len(bv), 512) self.assertEqual(bv.GetNumOnBits(), 20) bv = pyAvalonTools.GetAvalonFP(Chem.MolToMolBlock(Chem.MolFromSmiles('c1ccccc1')), False) self.assertEqual(bv.GetNumOnBits(), 8) def test4b(self): words = pyAvalonTools.GetAvalonFPAsWords(Chem.MolFromSmiles('c1ccccn1')) words2 = pyAvalonTools.GetAvalonFPAsWords(Chem.MolFromSmiles('Cc1ccccn1')) self.assertEqual(len(words), len(words2)) for i, word in enumerate(words): self.assertEqual(word & words2[i], word) def test5(self): m = Chem.MolFromSmiles('c1ccccc1C1(CC1)N') pyAvalonTools.Generate2DCoords(m) self.assertEqual(m.GetNumConformers(), 1) self.assertTrue(m.GetConformer(0).Is3D() == False) def test6(self): mb = pyAvalonTools.Generate2DCoords('c1ccccc1C1(CC1)N', True) m = Chem.MolFromMolBlock(mb) self.assertEqual(m.GetNumConformers(), 1) self.assertTrue(m.GetConformer(0).Is3D() == False) def testRDK151(self): smi = "C[C@H](F)Cl" m = Chem.MolFromSmiles(smi) temp = pyAvalonTools.GetCanonSmiles(smi, True) self.assertEqual(temp, smi) temp = pyAvalonTools.GetCanonSmiles(m) self.assertEqual(temp, smi) def testStruChk(self): smi_good = 'c1ccccc1C1(CC-C(C)C1)C' smi_bad = 'c1c(R)cccc1C1(CC-C(C)C1)C' r = pyAvalonTools.InitializeCheckMol(STRUCHK_INIT) self.assertEqual(r, 0) (err, fixed_mol) = pyAvalonTools.CheckMolecule(smi_good, True) self.assertEqual(err, 0) mol = Chem.MolFromSmiles(smi_good) (err, fixed_mol) = pyAvalonTools.CheckMolecule(mol) self.assertEqual(err, 0) (err, fixed_mol) = pyAvalonTools.CheckMoleculeString(smi_good, True) self.assertEqual(err, 0) self.assertNotEqual(fixed_mol, "") self.assertTrue(fixed_mol.find('M END') > 0) (err, fixed_mol) = pyAvalonTools.CheckMolecule(smi_bad, False) self.assertNotEqual(err, 0) self.assertFalse(fixed_mol) (err, fixed_mol) = pyAvalonTools.CheckMoleculeString(smi_bad, False) self.assertNotEqual(err, 0) self.assertFalse(fixed_mol) pyAvalonTools.CloseCheckMolFiles() def testStruChkInMemoryLog(self): r = pyAvalonTools.InitializeCheckMol(STRUCHK_INIT_IN_MEMORY_LOGGING) try: (err, fixed_mol) = pyAvalonTools.CheckMoleculeString(atom_clash, False) log = pyAvalonTools.GetCheckMolLog() self.assertTrue("of average bond length from bond" in log) # make sure that the log is cleared for the next molecule (err, fixed_mol) = pyAvalonTools.CheckMoleculeString("c1ccccc1", True) log = pyAvalonTools.GetCheckMolLog() self.assertFalse(log) finally: pyAvalonTools.CloseCheckMolFiles() # def testIsotopeBug(self): # mb="""D isotope problem.mol # Mrv0541 08141217122D # 4 3 0 0 0 0 999 V2000 # -3.2705 0.5304 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # -2.5561 0.9429 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # -1.8416 0.5304 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 # -2.5561 1.7679 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # 1 2 1 0 0 0 0 # 2 3 1 0 0 0 0 # 2 4 1 0 0 0 0 # M ISO 1 3 2 # M END # """ # csmi = pyAvalonTools.GetCanonSmiles(mb,False) # self.assertEqual(csmi,'[2H]C(C)C') # mb="""D isotope problem.mol # Mrv0541 08141217122D # 4 3 0 0 0 0 999 V2000 # -3.2705 0.5304 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # -2.5561 0.9429 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # -1.8416 0.5304 0.0000 H 2 0 0 0 0 0 0 0 0 0 0 0 # -2.5561 1.7679 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # 1 2 1 0 0 0 0 # 2 3 1 0 0 0 0 # 2 4 1 0 0 0 0 # M ISO 1 3 2 # M END # """ # csmi = pyAvalonTools.GetCanonSmiles(mb,False) # self.assertEqual(csmi,'[2H]C(C)C') # mb="""D isotope problem.mol # Mrv0541 08141217122D # 4 3 0 0 0 0 999 V2000 # -3.2705 0.5304 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # -2.5561 0.9429 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # -1.8416 0.5304 0.0000 D 0 0 0 0 0 0 0 0 0 0 0 0 # -2.5561 1.7679 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # 1 2 1 0 0 0 0 # 2 3 1 0 0 0 0 # 2 4 1 0 0 0 0 # M END # """ # csmi = pyAvalonTools.GetCanonSmiles(mb,False) # self.assertEqual(csmi,'[2H]C(C)C') # def testChiralPBug(self): # mb="""Untitled Document-1 # Mrv0541 08161213182D # 5 4 0 0 0 0 999 V2000 # -1.1196 1.1491 0.0000 P 0 0 2 0 0 0 0 0 0 0 0 0 # -0.4052 1.5616 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 # -1.9446 1.1491 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 # -1.3332 1.9460 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 # -0.7071 0.4346 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 # 1 2 1 0 0 0 0 # 1 3 1 0 0 0 0 # 1 4 2 0 0 0 0 # 1 5 1 1 0 0 0 # M END # """ # r = pyAvalonTools.InitializeCheckMol(STRUCHK_INIT) # self.assertEqual(r, 0) # (err, fixed_mol) = pyAvalonTools.CheckMolecule(mb, False) # self.assertEqual(err, 0) # self.assertTrue(fixed_mol) # self.assertNotEqual(fixed_mol.GetAtomWithIdx(0).GetChiralTag(),Chem.rdchem.ChiralType.CHI_UNSPECIFIED) def testAvalonCountFPs(self): # need to go to longer bit counts to avoid collions: cv1 = pyAvalonTools.GetAvalonCountFP('c1ccccc1', True, nBits=6000) cv2 = pyAvalonTools.GetAvalonCountFP('c1ccccc1.c1ccccc1', True, nBits=6000) for idx, v in cv1.GetNonzeroElements().items(): self.assertEqual(2 * v, cv2[idx]) cv1 = pyAvalonTools.GetAvalonCountFP(Chem.MolFromSmiles('c1ccccc1'), nBits=6000) cv2 = pyAvalonTools.GetAvalonCountFP(Chem.MolFromSmiles('c1ccccc1.c1ccccc1'), nBits=6000) for idx, v in cv1.GetNonzeroElements().items(): self.assertEqual(2 * v, cv2[idx]) if __name__ == '__main__': unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "External/AvalonTools/Wrap/testAvalonTools.py", "copies": "4", "size": "13457", "license": "bsd-3-clause", "hash": 5496098076825015000, "line_mean": 32.5586034913, "line_max": 211, "alpha_frac": 0.5750167199, "autogenerated": false, "ratio": 2.100031210986267, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9625433275700784, "avg_score": 0.009922931037096473, "num_lines": 401 }
# $Id$ # # Created by Greg Landrum, July 2008 # from rdkit import RDConfig import os import unittest from rdkit import DataStructs, Chem from rdkit.Avalon import pyAvalonTools struchk_conf_path = os.path.join(RDConfig.RDDataDir, 'struchk', '') struchk_log_path = '' STRUCHK_INIT = '''-ta %(struchk_conf_path)scheckfgs.trn -or -ca %(struchk_conf_path)scheckfgs.chk -cc -cl 3 -cs -cn 999 -l %(struchk_log_path)sstruchk.log'''%locals() def feq(v1,v2,tol=1e-4): return abs(v1-v2)<tol class TestCase(unittest.TestCase): def setUp(self) : pass def test1(self): m1 = Chem.MolFromSmiles('c1cccnc1') smi = pyAvalonTools.GetCanonSmiles(m1) self.failUnless(smi=='c1ccncc1') smi = pyAvalonTools.GetCanonSmiles('c1cccnc1',True) self.failUnless(smi=='c1ccncc1') def test2(self): tgts=['CC1=CC(=O)C=CC1=O','c2ccc1SC(=Nc1c2)SSC4=Nc3ccccc3S4','[O-][N+](=O)c1cc(Cl)c(O)c(c1)[N+]([O-])=O', 'N=C1NC=C(S1)[N+]([O-])=O','Nc3ccc2C(=O)c1ccccc1C(=O)c2c3', 'OC(=O)c1ccccc1C3=C2C=CC(=O)C(Br)=C2Oc4c3ccc(O)c4Br','CN(C)C2C(=O)c1ccccc1C(=O)C=2Cl', 'Cc3ccc2C(=O)c1ccccc1C(=O)c2c3[N+]([O-])=O',r'C/C(=N\O)/C(/C)=N/O', 'c1ccc(cc1)P(c2ccccc2)c3ccccc3'] d= file(os.path.join(RDConfig.RDDataDir,'NCI','first_200.props.sdf'),'r').read() mbs = d.split('$$$$\n')[:10] smis = [pyAvalonTools.GetCanonSmiles(mb,False) for mb in mbs] self.failUnless(smis==tgts) smis = [pyAvalonTools.GetCanonSmiles(smi,True) for smi in smis] self.failUnless(smis==tgts) def test3(self): bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ccccn1')) self.failUnlessEqual(len(bv),512) self.failUnlessEqual(bv.GetNumOnBits(),20) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ccccc1')) self.failUnlessEqual(bv.GetNumOnBits(),8) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1nnccc1')) self.failUnlessEqual(bv.GetNumOnBits(),30) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ncncc1')) self.failUnlessEqual(bv.GetNumOnBits(),27) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ncncc1'),nBits=1024) self.failUnlessEqual(len(bv),1024) self.failUnless(bv.GetNumOnBits()>27) def test4(self): bv = pyAvalonTools.GetAvalonFP('c1ccccn1',True) self.failUnlessEqual(bv.GetNumOnBits(),20) bv = pyAvalonTools.GetAvalonFP('c1ccccc1',True) self.failUnlessEqual(bv.GetNumOnBits(),8) bv = pyAvalonTools.GetAvalonFP('c1nnccc1',True) self.failUnlessEqual(bv.GetNumOnBits(),30) bv = pyAvalonTools.GetAvalonFP('c1ncncc1',True) self.failUnlessEqual(bv.GetNumOnBits(),27) bv = pyAvalonTools.GetAvalonFP('c1ncncc1',True,nBits=1024) self.failUnlessEqual(len(bv),1024) self.failUnless(bv.GetNumOnBits()>27) bv = pyAvalonTools.GetAvalonFP(Chem.MolToMolBlock(Chem.MolFromSmiles('c1ccccn1')),False) self.failUnlessEqual(len(bv),512) self.failUnlessEqual(bv.GetNumOnBits(),20) bv = pyAvalonTools.GetAvalonFP(Chem.MolToMolBlock(Chem.MolFromSmiles('c1ccccc1')),False) self.failUnlessEqual(bv.GetNumOnBits(),8) def test4b(self): words = pyAvalonTools.GetAvalonFPAsWords(Chem.MolFromSmiles('c1ccccn1')) words2 = pyAvalonTools.GetAvalonFPAsWords(Chem.MolFromSmiles('Cc1ccccn1')) self.failUnlessEqual(len(words),len(words2)) for i,word in enumerate(words): self.failUnlessEqual(word&words2[i],word) def test5(self): m = Chem.MolFromSmiles('c1ccccc1C1(CC1)N') pyAvalonTools.Generate2DCoords(m) self.failUnlessEqual(m.GetNumConformers(),1) self.failUnless(m.GetConformer(0).Is3D()==False) def test6(self): mb=pyAvalonTools.Generate2DCoords('c1ccccc1C1(CC1)N',True) m = Chem.MolFromMolBlock(mb) self.failUnlessEqual(m.GetNumConformers(),1) self.failUnless(m.GetConformer(0).Is3D()==False) def testRDK151(self): smi="C[C@H](F)Cl" m = Chem.MolFromSmiles(smi) temp = pyAvalonTools.GetCanonSmiles(smi,True) self.failUnlessEqual(temp,smi) temp = pyAvalonTools.GetCanonSmiles(m) self.failUnlessEqual(temp,smi) def testStruChk(self): smi_good='c1ccccc1C1(CC-C(C)C1)C' smi_bad='c1c(R)cccc1C1(CC-C(C)C1)C' r = pyAvalonTools.InitializeCheckMol(STRUCHK_INIT) self.failUnlessEqual(r, 0) (err, fixed_mol) = pyAvalonTools.CheckMolecule(smi_good, True) self.failUnlessEqual(err, 0) mol = Chem.MolFromSmiles(smi_good) (err, fixed_mol)=pyAvalonTools.CheckMolecule(mol) self.failUnlessEqual(err, 0) (err, fixed_mol)=pyAvalonTools.CheckMoleculeString(smi_good,True) self.failUnlessEqual(err, 0) self.failIfEqual(fixed_mol,"") self.failUnless(fixed_mol.find('M END')>0) (err, fixed_mol)=pyAvalonTools.CheckMolecule(smi_bad, False) self.failIfEqual(err, 0) self.failIf(fixed_mol) (err, fixed_mol)=pyAvalonTools.CheckMoleculeString(smi_bad, False) self.failIfEqual(err, 0) self.failIf(fixed_mol) pyAvalonTools.CloseCheckMolFiles() if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "External/AvalonTools/Wrap/testAvalonTools.py", "copies": "1", "size": "4992", "license": "bsd-3-clause", "hash": 8295806003435092000, "line_mean": 35.7058823529, "line_max": 109, "alpha_frac": 0.7005208333, "autogenerated": false, "ratio": 2.4339346660165773, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8533323823925125, "avg_score": 0.02022633507829045, "num_lines": 136 }
# $Id$ """Diameter.""" import struct import dpkt # Diameter Base Protocol - RFC 3588 # http://tools.ietf.org/html/rfc3588 # Request/Answer Command Codes ABORT_SESSION = 274 ACCOUTING = 271 CAPABILITIES_EXCHANGE = 257 DEVICE_WATCHDOG = 280 DISCONNECT_PEER = 282 RE_AUTH = 258 SESSION_TERMINATION = 275 class Diameter(dpkt.Packet): __hdr__ = ( ('v', 'B', 1), ('len', '3s', 0), ('flags', 'B', 0), ('cmd', '3s', 0), ('app_id', 'I', 0), ('hop_id', 'I', 0), ('end_id', 'I', 0) ) def _get_r(self): return (self.flags >> 7) & 0x1 def _set_r(self, r): self.flags = (self.flags & ~0x80) | ((r & 0x1) << 7) request_flag = property(_get_r, _set_r) def _get_p(self): return (self.flags >> 6) & 0x1 def _set_p(self, p): self.flags = (self.flags & ~0x40) | ((p & 0x1) << 6) proxiable_flag = property(_get_p, _set_p) def _get_e(self): return (self.flags >> 5) & 0x1 def _set_e(self, e): self.flags = (self.flags & ~0x20) | ((e & 0x1) << 5) error_flag = property(_get_e, _set_e) def _get_t(self): return (self.flags >> 4) & 0x1 def _set_t(self, t): self.flags = (self.flags & ~0x10) | ((t & 0x1) << 4) retransmit_flag = property(_get_t, _set_t) def unpack(self, buf): dpkt.Packet.unpack(self, buf) self.cmd = (ord(self.cmd[0]) << 16) | \ (ord(self.cmd[1]) << 8) | \ ord(self.cmd[2]) self.len = (ord(self.len[0]) << 16) | \ (ord(self.len[1]) << 8) | \ ord(self.len[2]) self.data = self.data[:self.len - self.__hdr_len__] l = [] while self.data: avp = AVP(self.data) l.append(avp) self.data = self.data[len(avp):] self.data = self.avps = l def pack_hdr(self): self.len = chr((self.len >> 16) & 0xff) + \ chr((self.len >> 8) & 0xff) + \ chr(self.len & 0xff) self.cmd = chr((self.cmd >> 16) & 0xff) + \ chr((self.cmd >> 8) & 0xff) + \ chr(self.cmd & 0xff) return dpkt.Packet.pack_hdr(self) def __len__(self): return self.__hdr_len__ + \ sum(map(len, self.data)) def __str__(self): return self.pack_hdr() + \ ''.join(map(str, self.data)) class AVP(dpkt.Packet): __hdr__ = ( ('code', 'I', 0), ('flags', 'B', 0), ('len', '3s', 0), ) def _get_v(self): return (self.flags >> 7) & 0x1 def _set_v(self, v): self.flags = (self.flags & ~0x80) | ((v & 0x1) << 7) vendor_flag = property(_get_v, _set_v) def _get_m(self): return (self.flags >> 6) & 0x1 def _set_m(self, m): self.flags = (self.flags & ~0x40) | ((m & 0x1) << 6) mandatory_flag = property(_get_m, _set_m) def _get_p(self): return (self.flags >> 5) & 0x1 def _set_p(self, p): self.flags = (self.flags & ~0x20) | ((p & 0x1) << 5) protected_flag = property(_get_p, _set_p) def unpack(self, buf): dpkt.Packet.unpack(self, buf) self.len = (ord(self.len[0]) << 16) | \ (ord(self.len[1]) << 8) | \ ord(self.len[2]) if self.vendor_flag: self.vendor = struct.unpack('>I', self.data[:4])[0] self.data = self.data[4:self.len - self.__hdr_len__] else: self.data = self.data[:self.len - self.__hdr_len__] def pack_hdr(self): self.len = chr((self.len >> 16) & 0xff) + \ chr((self.len >> 8) & 0xff) + \ chr(self.len & 0xff) data = dpkt.Packet.pack_hdr(self) if self.vendor_flag: data += struct.pack('>I', self.vendor) return data def __len__(self): length = self.__hdr_len__ + \ sum(map(len, self.data)) if self.vendor_flag: length += 4 return length if __name__ == '__main__': import unittest class DiameterTestCase(unittest.TestCase): def testPack(self): d = Diameter(self.s) self.failUnless(self.s == str(d)) d = Diameter(self.t) self.failUnless(self.t == str(d)) def testUnpack(self): d = Diameter(self.s) self.failUnless(d.len == 40) #self.failUnless(d.cmd == DEVICE_WATCHDOG_REQUEST) self.failUnless(d.request_flag == 1) self.failUnless(d.error_flag == 0) self.failUnless(len(d.avps) == 2) avp = d.avps[0] #self.failUnless(avp.code == ORIGIN_HOST) self.failUnless(avp.mandatory_flag == 1) self.failUnless(avp.vendor_flag == 0) self.failUnless(avp.len == 12) self.failUnless(len(avp) == 12) self.failUnless(avp.data == '\x68\x30\x30\x32') # also test the optional vendor id support d = Diameter(self.t) self.failUnless(d.len == 44) avp = d.avps[0] self.failUnless(avp.vendor_flag == 1) self.failUnless(avp.len == 16) self.failUnless(len(avp) == 16) self.failUnless(avp.vendor == 3735928559) self.failUnless(avp.data == '\x68\x30\x30\x32') s = '\x01\x00\x00\x28\x80\x00\x01\x18\x00\x00\x00\x00\x00\x00\x41\xc8\x00\x00\x00\x0c\x00\x00\x01\x08\x40\x00\x00\x0c\x68\x30\x30\x32\x00\x00\x01\x28\x40\x00\x00\x08' t = '\x01\x00\x00\x2c\x80\x00\x01\x18\x00\x00\x00\x00\x00\x00\x41\xc8\x00\x00\x00\x0c\x00\x00\x01\x08\xc0\x00\x00\x10\xde\xad\xbe\xef\x68\x30\x30\x32\x00\x00\x01\x28\x40\x00\x00\x08' unittest.main()
{ "repo_name": "insomniacslk/dpkt", "path": "dpkt/diameter.py", "copies": "17", "size": "5802", "license": "bsd-3-clause", "hash": -7997868579883412000, "line_mean": 31.0552486188, "line_max": 190, "alpha_frac": 0.4953464323, "autogenerated": false, "ratio": 2.827485380116959, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
# $Id$ # embedding sample for RVP, a part of RNV, http://davidashen.net/rnv.html # code kept simple to show the technique, not to provide a general purpose # module. # # details of the protocol are in a long comment near the start of rvp.c # import sys, os, string, re, xml.parsers.expat global rvpin,rvpout,pat,errors,parser,text,ismixed,prevline,prevcol # raised by resp if it gets something the module does not understand class ProtocolError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) # run RVP with grammar specified on the command line def launch(): global rvpin,rvpout inp,out=os.popen2('rvp '+string.join(sys.argv[1:],' ')) rvpin,rvpout=inp.fileno(),out.fileno() # os.read|os.write will be used # terminate string with zero, encode in utf-8 and then send to RVP def send(s): os.write(rvpin,s.encode('UTF-8')+'\0') # receive a zero-terminated response from RVP, zero byte is dropped def recv(): s='' while 1: s=s+os.read(rvpout,16) # 16 is good for ok responses, errors should be rare if(s[-1]=='\0'): break # last character in a response is always '\0' return s[:-1] # return current pattern value, and print error message on stderr, if any def resp(): global errors,prevline,prevcol r=string.split(recv(),' ',3) if(r[0]=='ok'): return r[1] if(r[0]=='error'): errors=1 if(r[3]!=''): # if the error string is empty, then error # is occured in erroneous state; don't report line,col=parser.ErrorLineNumber,parser.ErrorColumnNumber if(line!=prevline or col!=prevcol): # one report per file position sys.stderr.write(str(line)+","+str(col)+": "+r[3]) prevline,prevcol=line,col return r[1] if(r[0]=='er'): errors=1 return r[1] raise ProtocolError,"unexpected response '"+r[0]+"'" def start_tag_open(cur,name): send('start-tag-open '+cur+' '+name) return resp() def attribute(cur,name,val): send('attribute '+cur+' '+name+' '+val) return resp() def start_tag_close(cur,name): send('start-tag-close '+cur+' '+name) return resp() def end_tag(cur,name): send('end-tag '+cur+' '+name) return resp() def textonly(cur,text): send('text '+cur+' '+text) return resp() # in mixed content, whitespace is simply discarded, and any # non-whitespace is equal; but this optimization gives only # 5% increase in speed at most in practical cases def mixed(cur,text): if(re.search('[^\t\n ]',text)): send('mixed '+cur+' .') return resp() else: return cur def start(g): send('start '+g) return resp() def quit(): send('quit') return resp() # Expat handlers # If I remember correctly, Expat has the custom not to concatenate # text nodes; therefore CharDataHandler just concatenates them into # text, and then flush_text passes the text to the validator def flush_text(): global ismixed,pat,text if(ismixed): pat=mixed(pat,text) else: pat=textonly(pat,text) text='' def start_element(name,attrs): global ismixed,pat ismixed=1 flush_text() pat=start_tag_open(pat,name) ismixed=0 for n,v in attrs.items(): pat=attribute(pat,n,v) pat=start_tag_close(pat,name) def end_element(name): global ismixed,pat flush_text() pat=end_tag(pat,name) ismixed=1 def characters(data): global text text=text+data # Main errors=0 launch() pat=start('0') # that is, start of the first grammar; # multiple grammars can be passed to rvp parser=xml.parsers.expat.ParserCreate('UTF-8',':') # last colon in the name # separates local name from namespace URI parser.StartElementHandler=start_element parser.EndElementHandler=end_element parser.CharacterDataHandler=characters text='' prevline,prevcol=-1,-1 parser.ParseFile(sys.stdin) quit() # this stops RVP; many files can be validated with a single RVP # running, concurrently or sequentially sys.exit(errors)
{ "repo_name": "rhorenov/rnv", "path": "tools/rvp.py", "copies": "2", "size": "3923", "license": "bsd-3-clause", "hash": -7634109448142750000, "line_mean": 25.3288590604, "line_max": 79, "alpha_frac": 0.6839153709, "autogenerated": false, "ratio": 3.189430894308943, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4873346265208943, "avg_score": null, "num_lines": null }
#$Id$ from books.model.Address import Address from books.model.DefaultTemplate import DefaultTemplate class Contact: """This class is used to create object for contacts.""" def __init__(self): """Initialize the parameters for contacts object.""" self.contact_id = '' self.contact_name = '' self.company_name = '' self.contact_salutation = '' self.has_transaction = None self.contact_type = '' self.is_crm_customer = None self.primary_contact_id = '' self.price_precision = 0 self.payment_terms = 0 self.payment_terms_label = '' self.currency_id = '' self.currency_code = '' self.currency_symbol = '' self.outstanding_receivable_amount = 0.00 self.outstanding_receivable_amount_bcy = 0.00 self.outstanding_payable_amount = 0.00 self.outstanding_payable_amount_bcy = 0.00 self.unused_credits_receivable_amount = 0.00 self.unused_credits_receivable_amount_bcy = 0.00 self.unused_credits_payable_amount = 0.00 self.unused_credits_payable_amount_bcy = 0.00 self.status = '' self.payment_reminder_enabled = None self.notes = '' self.created_time = '' self.last_modified_time = '' self.first_name = '' self.last_name = '' self.email = '' self.phone = '' self.mobile = '' self.custom_fields = [] self.track_1099 = None self.tax_id_type = '' self.tax_id_value = '' self.billing_address = Address() self.shipping_address = Address() self.contact_persons = [] self.default_templates = DefaultTemplate() def set_contact_id(self, contact_id): """Set contact id for the contact. Args: contact_id(str): Contact id of the contact. """ self.contact_id = contact_id def get_contact_id(self): """Get contact_id of the contact. Returns: str: Contact id of the contact. """ return self.contact_id def set_contact_name(self, contact_name): """Set contact name for the contact. Args: contact_name(str): Contact name of the contact. """ self.contact_name = contact_name def get_contact_name(self): """Get contact name of the contact. Returns: str: Contact name of the contact. """ return self.contact_name def set_has_transaction(self, has_transaction): """Set whether the contact has transaction or not. Args: has_transaction(bool): True if the contact has transactions else False. """ self.has_transaction = has_transaction def get_has_transaction(self): """Get whether the contact has transaction or not. Returns: bool: True if the contact has transactions else False. """ return self.has_transaction def set_contact_type(self, contact_type): """Set contact type of the contact. Args: contact_type(str): Contact type of the contact. """ self.contact_type = contact_type def get_contact_type(self): """Get contact type of the contact. Returns: str: Contact type of the contact. """ return self.contact_type def set_is_crm_customer(self, is_crm_customer): """Set whether the contact is crm customer or not. Args: is_crm_customer(bool): True if the contact is crm customer else False. """ self.is_crm_customer = is_crm_customer def get_is_crm_customer(self): """Get whether the contact is crm customer or not. Returns: bool: True if the contact is crm customer else False . """ return self.is_crm_customer def set_primary_contact_id(self, primary_contact_id): """Set primary contact id for the contact. Args: primary_contact_id(str): Primary contact id for the contact. """ self.primary_conatact_id = primary_contact_id def get_primary_conatact_id(self): """Get primary contact id for the contact. Returns: str: Primary contact id for the contact. """ return self.primary_conatact_id def set_payment_terms(self, payment_terms): """Set payment terms for the contact. Args: payment_terms(int): Payment terms for the contact. """ self.payment_terms = payment_terms def get_payment_terms(self): """Get payment terms of the contact. Returns: int: Payment terms of the contact. """ return self.payment_terms def set_payment_terms_label(self, payment_terms_label): """Set payment terms label for the contact. Args: payment_terms_label(str): Payment terms for the contact. """ self.payment_terms_label = payment_terms_label def get_payment_terms_label(self): """Get payment terms label of the contact. Returns: str: Payment terms label of the contact. """ return self.payment_terms_label def set_currency_id(self, currency_id): """ Set currency id for the contact. Args: currency_id(str): Currency id for the contact. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id of the contact. Args: currency_id(str): Currency id for the contact. """ return self.currency_id def set_currency_code(self, currency_code): """Set currency code for the contact. Args: currency_code(str): Currency code for the contact. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code of the contact. Returns: str: Currency code of the contact. """ return self.currency_code def set_currency_symbol(self, currency_symbol): """Set currency symbol for the contact. Args: currency_symbol(str): Currency symbol for the contact. """ self.currency_symbol = currency_symbol def get_currency_symbol(self): """Get currency symbol of the contact. Returns: str: Currency symbol of the contact. """ return self.currency_symbol def set_outstanding_receivable_amount(self, outstanding_receivable_amount): """Set outstanding receivable amount for the contact. Args: outstanding_receivable_amount(float): Outstanding receivable amount for the contact. """ self.outstanding_receivable_amount = outstanding_receivable_amount def get_outstanding_receivable_amount(self): """Get outstanding receivable amount of the contact. Returns: float: Outstanding receivable amount of the contact. """ return self.outstanding_receivable_amount def set_outstanding_receivable_amount_bcy(self, \ outstanding_receivable_amount_bcy): """Set outstanding receivable amount bcy for the contact. Args: outstanding_receivable_amount_bcy(float): Outstanding receivable amount bcy for the contact. """ self.outstanding_receivable_amount_bcy = \ outstanding_receivable_amount_bcy def get_outstanding_receivable_amount_bcy(self): """Get the outstanding receivable amount bcy of the contact. Returns: float: Outstanding receivable amount bcy of the contact. """ return self.outstanding_receivable_amount_bcy def set_outstanding_payable_amount(self, outstanding_payable_amount): """Set the outstanding payable amount for the contact. Args: outstanding_payable_amount(float): Outstanding payable amount for the contact. """ self.outstanding_payable_amount = outstanding_payable_amount def get_outstanding_payable_amount(self): """Get the outstanding payable amount of the contact. Returns: float: Outstanding payable amount of the contact. """ return self.outstanding_payable_amount def set_outstanding_payable_amount_bcy(self, \ outstanding_payable_amount_bcy): """Set outstanding payable amount bcy for the contact. Args: outstanding_payable_amount_bcy(float): Outstanding payable amount bcy for the contact. """ self.outstanding_payable_amount_bcy = outstanding_payable_amount_bcy def get_outstanding_payable_amount_bcy(self): """Get outstanding payable amount bcy of the contact. Returns: float: Outstanding payable amount bcy of the contact. """ return self.outstanding_payable_amount_bcy def set_unused_credits_receivable_amount(self, \ unused_credits_receivable_amount): """Set unused credits receivable amount for the contact. Args: unused_credits_receivable_amount(float): Unused credits receivable amount for the contact. """ self.unused_credits_receivable_amount = \ unused_credits_receivable_amount def get_unused_credits_receivable_amount(self): """Get unused credits receivable amount of the contact. Returns: float: Unused credits receivable amount for the contact. """ return self.unused_credits_receivable_amount def set_unused_credits_receivable_amount_bcy(self, \ unused_credits_receivable_amount_bcy): """Set unused credits receivable amount bcy for the contact. Args: unused_credits_receivable_amount_bcy(float): Unused credits receivable amount bcy for the contact. """ self.unused_credits_receivable_amount_bcy = \ unused_credits_receivable_amount_bcy def get_unused_credits_receivable_amount_byc(self): """Get unused credits receivable amount bcy of the contact. Returns: float: Unused credits receivable amount bcy of the contact. """ return self.unused_credits_receivable_amount_bcy def set_unused_credits_payable_amount(self, unused_credits_payable_amount): """Set unused credits payable amount for the contact. Args: unused_credits_payable_amount(float): Unused credits payable amount for the contact. """ self.unused_credits_payable_amount = unused_credits_payable_amount def get_unused_credits_payable_amount(self): """Get unused payable amount of the contact. Returns: float: Unused payable amount of the contact. """ return self.unused_credits_payable_amount def set_unused_credits_payable_amount_bcy(self, \ unused_credits_payable_amount_bcy): """Set unused credits payable amount bcy for the contact. Args: unused_credits_payable_amount_bcy(float): Unused credits payable amount bcy for the contact. """ self.unused_credits_payable_amount_bcy = \ unused_credits_payable_amount_bcy def get_unused_credits_payable_amount_bcy(self): """Get unused credits payable amount bcy of the contact. Returns: float: Unused credits payable amount bcy of the contact. """ return self.unused_credits_payable_amount_bcy def set_status(self, status): """Set status for the contact. Args: status(str): Status of the contact. """ self.status = status def get_status(self): """Get status of the contact. Returns: str: Status of the contact. """ return self.status def set_payment_reminder_enabled(self, payment_reminder_enabled): """Set whether to enabe payment reminder for the contact. Args: payment_reminder_enabled(bool): True if enable payment reminder else false. """ self.payment_reminder_enabled = payment_reminder_enabled def get_payment_reminder_enabled(self): """Get whether the payment reminder is enabled or not Returns: bool: True if payment reminder is enabled else false. """ return self.payment_reminder_enabled def set_notes(self, notes): """Set notes for the contact. Args: notes(str): Notes for contact. """ self.notes = notes def get_notes(self): """Get notes of the contact. Returns: str: Notes of the contact. """ return self.notes def set_created_time(self, created_time): """Set created time for the contact. Args: created_time(str): Created time for the contact. """ self.created_time = created_time def get_created_time(self): """Get created of the contact. Returns: str: Created time of the contact. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time for the contact. Args: last_modified_time(str): Last modified time for the contact. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time of the contact. Returns: str: Last modified time of the contact. """ return self.last_modified_time def set_billing_address(self, billing_address): """Set billing address for the contact. Args: billing_address(str): Billing address for the contact. """ self.billing_address = billing_address def get_billing_address(self): """Get billing address of the contact. Returns: str: Billing address of the contact. """ return self.billing_address def set_shipping_address(self, shipping_address): """Set shipping address for the contact. Args: shipping_address(str): Shipping address for the contact. """ self.shipping_address = shipping_address def get_shipping_address(self): """Get shipping address of the contact. Returns: str: Shipping address of the contact. """ return self.shipping_address def set_contact_persons(self, contact_person): """Set contact persons for the contact. Args: contact_person(list): List of contact persons object. """ self.contact_persons.extend(contact_person) def get_contact_persons(self): """Get contact persons of a contact. Returns: list: List of contact persons. """ return self.contact_persons def set_default_templates(self, default_templates): """Set default templates for the contact. Args: default_templates(instance): Default templates object. """ self.default_templates = default_templates def get_default_templates(self): """Get default templates of the contact. Returns: instance: Default templates instance. """ return self.default_templates def set_custom_fields(self, custom_field): """Set custom fields for a contact. Args: custom_field(instance): Custom field object. """ self.custom_fields.append(custom_field) def get_custom_fields(self): """Get custom fields of the contact. Returns: instance: Custom field of the contact. """ return self.custom_fields def set_company_name(self, company_name): """Set company name for the contact. Args: company_name(str): Company name of the contact. """ self.company_name = company_name def get_company_name(self): """Get company name of the contact. Returns: str: cCompany name of the contact. """ return self.company_name def set_contact_salutation(self, contact_salutation): """Set salutation for the contact. Args: contact_salutation(str): Salutation of the contact. """ self.contact_salutation = contact_salutation def get_contact_salutation(self): """Get salutation of the contact. Returns: str: Salutation of the contact """ return self.contact_salutation def set_price_precision(self, price_precision): """Set price precision for the contact. Args: price_precision(int): Price precision for the contact. """ self.price_precision = price_precision def get_price_precision(self): """Get price precision of the contact. Returns: int: Price precision of the contact. """ return self.price_precision def set_track_1099(self, track_1099): """Set to track a contact for 1099 reporting. Args: track_1099(bool): True to track a contact for 1099 reporting else False. """ self.track_1099 = track_1099 def get_track_1099(self): """Get whether a contact is set for 1099 tracking. Returns: bool: True if a contact is set for 1099 tracking else False. """ return self.track_1099 def set_tax_id_type(self, tax_id_type): """Set tax id type for a contact. Args: tax_id_type(str): tax id type for a contact """ self.tax_id_type = tax_id_type def get_tax_id_type(self): """Get tax id type of a contact. Returns: str: Tax id type for a contact. """ return self.tax_id_type def set_tax_id_value(self, tax_id_value): """Set tax id value for a contact. Args: tax_id_value(str): Tax id value for a contact. """ self.tax_id_value = tax_id_value def get_tax_id_value(self): """Get tax id value of a contact. Returns: str: Tax id value of a contact. """ return self.tax_id_value def set_first_name(self, first_name): """Set first name. Args: first_name = First name. """ self.first_name = first_name def get_first_name(self): """Get first name. Returns: str: First name. """ return self.first_name def set_last_name(self, last_name): """Set last name. Args: last_name = Last name. """ self.last_name = last_name def get_last_name(self): """Get last name. Returns: str: Last name. """ return self.last_name def set_email(self, email): """Set email. Args: email(str): Email. """ self.email = email def get_email(self): """Get email. Returns: str: Email. """ return self.email def set_phone(self, phone): """Set phone. Args: phone(str): Phone. """ self.phone = phone def get_phone(self): """Get phone. Returns: str: Phone. """ return self.phone def set_mobile(self, mobile): """Set mobile. Args: mobile(str): Mobile. """ self.mobile = mobile def to_json(self): """This method is used to convert the contact object to JSON object. Returns: dict: Dictionary containing details of contact object. """ data = {} if self.contact_name != '': data['contact_name'] = self.contact_name if self.payment_terms != '': data['payment_terms'] = self.payment_terms if self.payment_terms_label != '': data['payment_terms_label'] = self.payment_terms_label if self.currency_id != '': data['currency_id'] = self.currency_id if self.billing_address is not None: billing_address = self.billing_address data['billing_address'] = billing_address.toJSON() if self.shipping_address is not None: shipping_address = self.shipping_address data['shipping_address'] = shipping_address.toJSON() if self.contact_persons: data['contact_persons'] = [] for value in self.contact_persons: data['contact_persons'].append(value.toJSON()) if self.notes != '': data['notes'] = self.notes return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Contact.py", "copies": "1", "size": "21991", "license": "mit", "hash": -8311363638895458000, "line_mean": 26.1159062885, "line_max": 79, "alpha_frac": 0.563093993, "autogenerated": false, "ratio": 4.3798048197570205, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.544289881275702, "avg_score": null, "num_lines": null }
#$Id$ from books.model.Address import Address class Bill: """This class is used to create an object for Bills.""" def __init__(self): """Initialize the parameters for bills object.""" self.bill_id = '' self.bill_payment_id = '' self.vendor_id = '' self.vendor_name = '' self.unused_credits_payable_amount = 0.0 self.status = '' self.bill_number = '' self.date = '' self.due_date = '' self.due_days = '' self.reference_number = '' self.due_by_days = 0 self.due_in_days = '' self.currency_id = '' self.currency_code = '' self.currency_symbol = '' self.price_precision = 0 self.exchange_rate = 0.0 self.line_items = [] self.sub_total = 0.0 self.tax_total = 0.0 self.total = 0.0 self.taxes = [] self.amount_applied = 0.0 self.payment_made = 0.0 self.balance = 0.0 self.billing_address = Address() self.payments = [] self.created_time = '' self.last_modified_time = '' self.reference_id = '' self.attachment_name = '' self.account_id = '' self.description = '' self.rate = 0.0 self.quantity = 0.0 self.tax_id = '' self.notes = '' self.terms = '' def set_bill_id(self, bill_id): """Set bill id. Args: bill_id(str): Bill id. """ self.bill_id = bill_id def get_bill_id(self): """Get bill id. Returns: str: Bill id. """ return self.bill_id def set_bill_payment_id(self, bill_payment_id): """Set bill payment id. Args: bill_payment_id(str): Bill payment id. """ self.bill_payment_id = bill_payment_id def get_bill_payment_id(self): """Get bill payment id. Returns: str: Bill payment id. """ return self.bill_payment_id def set_amount_applied(self, amount_applied): """Set amount applied. Args: amount_applied(float): Amount applied. """ self.amount_applied = amount_applied def get_amount_applied(self): """Get amount applied. Returns: float: Amount applied. """ return self.amount_applied def set_vendor_id(self, vendor_id): """Set vendor id. Args: vendor_id(str): Vendor id. """ self.vendor_id = vendor_id def get_vendor_id(self): """Get vendor id. Returns: str: Vendor id. """ return self.vendor_id def set_vendor_name(self, vendor_name): """Set vendor name. Args: vendor_name(str): Vendor name. """ self.vendor_name = vendor_name def get_vendor_name(self): """Get vendor name. Returns: str: Vendor name. """ return self.vendor_name def set_unused_credits_payable_amount(self, unused_credits_payable_amount): """Set unused amount payable amount. Args: unused_credits_payable_amount(float): Unused amount payable amount. """ self.unused_credits_payable_amount = unused_credits_payable_amount def get_unused_payable_amount(self): """Get unused amount payable amount. Returns: float: Unused amount payable amount. """ return self.unused_credits_payable_amount def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_bill_number(self, bill_number): """Set bill number. Args: bill_number(str): Bill number. """ self.bill_number = bill_number def get_bill_number(self): """Get bill number. Returns: str: Bill number. """ return self.bill_number def set_reference_number(self, reference_number): """Set reference number. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number. Returns: str: Reference number. """ return self.reference_number def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_due_date(self, due_date): """Set due date. Args: due_date(str): Due date. """ self.due_date = due_date def get_due_date(self): """Get due date. Returns: str: Due date. """ return self.due_date def set_due_by_days(self, due_by_days): """Set due by days. Args: due_by_days(int): Due by days. """ self.due_by_days = due_by_days def get_due_by_days(self): """Get due by days. Returns: int: Due by days. """ return self.due_by_days def set_due_in_days(self, due_in_days): """Set due in days. Args: due_in_days(str): Due in days. """ self.due_in_days = self.due_in_days def get_due_in_days(self): """Get due in days. Returns: str: Due in days. """ return self.due_in_days def set_currency_id(self, currency_id): """Set currency_id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return currency_id def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code. Returns: str: Currency code. """ return self.currency_code def set_currency_symbol(self, currency_symbol): """Set currency symbol. Args: currency_symbol(str): Currency symbol. """ self.currency_symbol = currency_symbol def get_currency_symbol(self): """Get currency symbol. Returns: str: Currency symbol. """ return self.currency_symbol def set_price_precision(self, price_precision): """Set price precision. Args: price_precision(int): Price precision. """ self.price_precision = price_precision def get_price_precision(self): """Get price precision. Returns: int: Price precision. """ return self.price_precision def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_line_items(self, line_item): """Set line items. Args: line_item(instance): Line item object. """ self.line_items.append(line_item) def get_line_items(self): """Get line items. Returns: list of instance: List of line items object. """ return self.line_items def set_sub_total(self, sub_total): """Set sub total. Args: sub_total(float): Sub total. """ self.sub_total = sub_total def get_sub_total(self): """Get sub total. Returns: float: Sub total. """ return self.sub_total def set_tax_total(self, tax_total): """Set tax total. Args: tax_total(float): Tax total. """ self.tax_total = tax_total def get_tax_total(self): """Get tax total. Returns: tax_total(float): Tax total. """ return self.tax_total def set_total(self, total): """Set total. Args: total(float): Total. """ self.total = total def get_total(self): """Get total. Returns: float: Total. """ return self.total def set_taxes(self, tax): """Set taxes. Args: tax(instance): Tax object. """ self.taxes.append(tax) def get_taxes(self): """Get taxes. Returns: list of instance: List of tax object. """ return self.taxes def set_payment_made(self, payment_made): """Set payment made. Args: payment_made(float): Payment made. """ self.payment_made = payment_made def get_payment_made(self): """Get payment made. Returns: float: Payment made. """ return self.payment_made def set_balance(self, balance): """Set balance. Args: balance(float): Balance. """ self.balance = balance def get_balance(self): """Get balance. Returns: float: Balance. """ return self.balance def set_billing_address(self, billing_address): """Set billling address, Args: billing_address(instance): Billing address object. """ self.billing_address = billing_address def get_billing_address(self): """Get billing address. Returns: instance: Billing address object. """ return self.billing_address def set_payments(self, payments): """Set payments. Args: payments(instance): Payments object. """ self.payments.append(payment) def get_payments(self): """Get payments. Returns: list of instance: List of payments object. """ return self.payments def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time. Args: last_modified_time(str): Last modified time. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time. Returns: str: Last modified time. """ return self.last_modified_time def set_reference_id(self, reference_id): """Set reference id. Args: reference_id(str): Reference id. """ self.reference_id = reference_id def get_reference_id(self): """Get reference id. Returns: str: Reference id. """ return self.reference_id def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_terms(self, terms): """Set terms. Args: terms(str): Terms. """ self.terms = terms def get_terms(self): """Get terms. Returns: str: Terms. """ return self.terms def set_attachment_name(self, attachment_name): """Set attachment name. Args: attachment_name(str): Attachment name. """ self.attachment_name = attachment_name def get_attachment_name(self): """Get attachment name. Returns: str: Attachment name. """ return self.attachment_name def set_account_id(self, account_id): """Set account id. Args: account_id(str): Account id. """ self.account_id = account_id def get_account_id(self): """Get account id. Returns: str: Account id. """ return self.account_id def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_rate(self, rate): """Set rate. Args: rate(float): Rate. """ self.rate = rate def get_rate(self): """Get rate. Returns: float: Rate. """ return self.rate def set_quantity(self, quantity): """Set quantity. Args: quantity(float): Quantity. """ self.quantity = quantity def get_quantity(self): """Get quantity. Returns: float: Quantity. """ return self.quantity def set_tax_id(self, tax_id): """Set tax id. Args: tax_id(str): Tax id. """ self.tax_id = tax_id def get_tax_id(self): """Get tax id. Returns: str: Tax id. """ return self.tax_id def set_due_days(self, due_days): """Set due days. Args: due_days(str): Due days. """ self.due_days = due_days def get_due_days(self): """Get due days. Returns: str: Due days. """ return self.due_days def to_json(self): """This method is used to convert bill object to json object. Returns: dict: Dictionary containing json object for Bills. """ data = {} if self.bill_id != '': data['bill_id'] = self.bill_id if self.amount_applied > 0: data['amount_applied'] = self.amount_applied if self.vendor_id != '': data['vendor_id'] = self.vendor_id if self.bill_number != '': data['bill_number'] = self.bill_number if self.reference_number != '': data['reference_number'] = self.reference_number if self.date != '': data['date'] = self.date if self.due_date != '': data['due_date'] = self.due_date if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.line_items: data['line_items'] = [] for value in self.line_items: line_item = value.to_json() data['line_items'].append(line_item) if self.notes != '': data['notes'] = self.notes if self.terms != '': data['terms'] = self.terms return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Bill.py", "copies": "1", "size": "15836", "license": "mit", "hash": 4441708760373698600, "line_mean": 18.9949494949, "line_max": 79, "alpha_frac": 0.4969689315, "autogenerated": false, "ratio": 4.165176223040505, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.027980572256324776, "num_lines": 792 }
#$Id$ from books.model.Address import Address class CreditNote: """This class creates object for credit notes.""" def __init__(self): """This class is used to create object for credit notes.""" self.creditnote_id = '' self.creditnote_number = '' self.date = '' self.status = '' self.reference_number = '' self.customer_id = '' self.customer_name = '' self.contact_persons = [] self.currency_id = '' self.currency_code = '' self.exchange_rate = 0.0 self.price_precision = 0 self.template_id = '' self.template_name = '' self.is_emailed = True self.line_items = [] self.sub_total = 0.0 self.total = 0.0 self.total_credits_used = 0.0 self.total_refunded_amount = 0.0 self.balance = 0.0 self.taxes = [] self.notes = '' self.terms = '' self.billing_address = Address() self.shipping_address = Address() self.created_time = '' self.last_modified_time = '' self.refund_mode = '' self.amount = '' self.from_account_id = '' self.description = '' def set_creditnote_id(self, creditnote_id): """Set creditnote id. Args: creditnote_id(str): Credit note id. """ self.creditnote_id = creditnote_id def get_creditnote_id(self): """Get creditnote id. Returns: str: Creditnote id. """ return self.creditnote_id def set_creditnote_number(self, creditnote_number): """Set creditnote number. Args: creditnote_number(str):Creditnote number. """ self.creditnote_number = creditnote_number def get_creditnote_number(self): """Get creditnote number. Returns: str: Creditnote number. """ return self.creditnote_number def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_reference_number(self, reference_number): """Set reference number. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number. Returns: str: Reference number. """ return self.reference_number def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customerid. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_contact_persons(self, contact_person): """Set contact person. Args: contact_person(list): Contact person. """ self.contact_persons.extend(contact_person) def get_contact_persons(self): """Get contact persons. Returns: list of instance: List of contact person object. """ return self.contact_persons def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currenccy code. Returns: str: Currecny code. """ return self.currency_code def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange ratte. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_price_precision(self, price_precision): """Set price precision. Args: price_precision(float): Price precision. """ self.price_precision = price_precision def get_price_precision(self): """Get price precision. Returns: float: Price precision. """ return self.price_precision def set_template_id(self, template_id): """Set template id. Args: template_id(str): Template id. """ self.template_id = template_id def get_template_id(self): """Get template id. Returns: str: Template id. """ return self.template_id def set_template_name(self, template_name): """Set template name. Args: template_name(str): Template name. """ self.template_name = template_name def get_template_name(self): """Get template name. Returns: str: Template name. """ return self.template_name def set_is_emailed(self, is_emailed): """Set whether is emailed or not. Args: is_emailed(bool): True if emailed else False. """ self.is_emailed = is_emailed def get_is_emailed(self): """Get whether is emailed or not. Returns: bool: True if emailed else False. """ return self.is_emailed def set_line_items(self, line_items): """Set line items. Args: line_items(instance): Line items object. """ self.line_items.append(line_items) def get_line_items(self): """Get line items. Returns: list of instance: List of lineitems object. """ return self.line_items def set_sub_total(self, sub_total): """Set sub total. Args: sub_total(float): Sub total. """ self.sub_total = sub_total def get_sub_total(self): """Get sub total. Returns: float: Sub total. """ return self.sub_total def set_total(self, total): """Set total. Args: total(float): Total. """ self.total = total def get_total(self): """Get total. Returns: float: Total. """ return self.total def set_total_credits_used(self, total_credits_used): """Set total credits used. Args: total_credits_used(float): Total credits used. """ self.total_credits_used = total_credits_used def get_total_credits_used(self): """Get total credits used. Returns: float: Total credits used. """ return self.total_credits_used def set_total_refunded_amount(self, total_refunded_amount): """Set total refunded amount. Args: total_refunded_amount(float): Total refunded amount. """ self.total_refunded_amount = total_refunded_amount def get_total_refunded_amount(self): """Get total refunded amount. Returns: float: Total refunded amount. """ return self.total_refunded_amount def set_balance(self, balance): """Set balance. Args: balance(float): Balance. """ self.balance = balance def get_balance(self): """Get balance. Returns: float: Balance. """ return self.balance def set_taxes(self, taxes): """Set taxes. Args: taxes(list of instance): List of tax object. """ self.taxes.extend(taxes) def get_taxes(self): """Get taxes. Returns: list: List of objects. """ return self.taxes def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_terms(self, terms): """Set terms. Args: terms(str): Terms. """ self.terms = terms def get_terms(self): """Get terms. Returns: str: Terms. """ return self.terms def set_shipping_address(self, address): """Set shipping address. Arg: address(instance): Address object. """ self.shipping_address = address def get_shipping_address(self): """Get shipping address. Returns: instance: Address object. """ return self.shipping_address def set_billing_address(self, address): """Set billing address. Args: address: Address object. """ self.billing_address = address def get_billing_address(self): """Get billing address. Returns: instance: Address object. """ return self.billing_address def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created ime. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time. Args: last_modified_time(str): Last modified time. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time. Returns: str: Last modifiedd time. """ return self.last_modified_time def set_refund_mode(self, refund_mode): """Set refund mode. Args: refund_mode(str): Refund mode. """ self.refund_mode = refund_mode def get_refund_mode(self): """Get refund mode. Returns: str: Refund mode. """ return self.refund_mode def set_amount(self, amount): """Set amount. Args: amount(float): Amount. """ self.amount = amount def get_amount(self): """Get amount. Returns: float: Amount. """ return self.amount def set_from_account_id(self, from_account_id): """Set from account id. Args: from_account_id(str): From account id. """ self.from_account_id = from_account_id def get_from_account_id(self): """Get from account id. Returns: str: From account id. """ return self.from_account_id def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def to_json(self): """This method is used to convert credit notes object to json object. Returns: dict: Dictionary containing json object for credit notes. """ data = {} if self.customer_id != '': data['customer_id'] = self.customer_id if self.contact_persons: data['contact_persons'] = self.contact_persons if self.reference_number != '': data['reference_number'] = self.reference_number if self.template_id != '': data['template_id'] = self.template_id if self.date != '': data['date'] = self.date if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.line_items: data['line_items'] = [] for value in self.line_items: line_item = value.to_json() data['line_items'].append(line_item) if self.notes != '': data['notes'] = self.notes if self.terms != '': data['terms'] = self.terms if self.creditnote_number != '': data['creditnote_number'] = self.creditnote_number return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/CreditNote.py", "copies": "1", "size": "13605", "license": "mit", "hash": 5281439057000843000, "line_mean": 19.9307692308, "line_max": 77, "alpha_frac": 0.5159132672, "autogenerated": false, "ratio": 4.302656546489564, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5318569813689564, "avg_score": null, "num_lines": null }
#$Id$ from books.model.Address import Address class Estimate: """This class is used to create object for estimates.""" def __init__(self): """Initialize parameters for Estimates object.""" self.estimate_id = '' self.estimate_number = '' self.date = '' self.reference_number = '' self.status = '' self.customer_id = '' self.customer_name = '' self.contact_persons = [] self.currency_id = '' self.currency_code = '' self.exchange_rate = 0.00 self.expiry_date = '' self.discount = 0.00 self.is_discount_before_tax = None self.discount_type = '' self.line_items = [] self.shipping_charge = 0.00 self.adjustment = 0.00 self.adjustment_description = '' self.sub_total = 0.0 self.total = 0.0 self.tax_total = 0.0 self.price_precision = 0 self.taxes = [] self.billing_address = Address() self.shipping_address = Address() self.notes = '' self.terms = '' self.custom_fields = [] self.template_id = '' self.template_name = '' self.created_time = '' self.last_modified_time = '' self.salesperson_id = '' self.salesperson_name = '' self.accepted_date = '' self.declined_date = '' def set_estimate_id(self, estimate_id): """Set estimate id. Args: estimate_id(str): Estimate id. """ self.estimate_id = estimate_id def get_estimate_id(self): """Get estimate id. Returns: str: Estimate id. """ return self.estimate_id def set_estimate_number(self, estimate_number): """Set estimate number. Args: estimate_number(str): Estimate number. """ self.estimate_number = estimate_number def get_estimate_number(self): """Get estimate number. Returns: str: Estimate number. """ return self.estimate_number def set_date(self, date): """Set the date for estimate. Args: date(str): Date for estimate. """ self.date = date def get_date(self): """Get the date of estimate. Returns: str: Date of estimate. """ return self.date def set_reference_number(self, reference_number): """Set reference number. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number. Returns: str: Reference number. """ return self.reference_number def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_contact_persons(self, contact_person): """Set contact person. Args: contact_person(list of instance): List of contact person object. """ self.contact_persons.extend(contact_person) def get_contact_persons(self): """Get contact person. Returns: list: List of contact person object. """ return self.contact_persons def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code. Returns: str: Currency code. """ return self.currency_code def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_expiry_date(self, expiry_date): """Set expiry date. Args: expiry_date(str): Expiry date. """ self.expiry_date = expiry_date def get_expiry_date(self): """Get expiry date. Returns: str: Expiry date. """ return self.expiry_date def set_discount(self, discount): """Set discount. Args: discount(float): Discount. """ self.discount = discount def get_discount(self): """Get discount. Returns: str: Discount. """ return self.discount def set_is_discount_before_tax(self, is_discount_before_tax): """Set whether to discount before tax or not. Args: is_discount_before_tax(bool): True to discount before tax. """ self.is_discount_before_tax = is_discount_before_tax def get_is_discount_before_tax(self): """Get whether to discount before tax or not. Returns: bool: True to discount before tax. """ return self.is_discount_before_tax def set_discount_type(self, discount_type): """Set type of discount. Args: discount_type(str): Discount type. """ self.discount_type = discount_type def get_discount_type(self): """Get type of discount. Returns: str: Discount type. """ return self.discount_type def set_line_items(self, items): """Set line items. Args: items(instance): Line items object. """ self.line_items.append(items) def get_line_items(self): """Get line items. Returns: list of instance: List of line items object. """ return self.line_items def set_shipping_charge(self, shipping_charge): """Set shipping charge. Args: shipping_charge(float): Shipping charge. """ self.shipping_charge = shipping_charge def get_shipping_charge(self): """Get shipping charge. Returns: float: Shipping charge. """ return self.shipping_charge def set_adjustment(self, adjustment): """Set adjustment. Args: adjustment(float): Adjustment. """ self.adjustment = adjustment def get_adjustment(self): """Get adjustment. Returns: float: Adjustment. """ return self.adjustment def set_adjustment_description(self, adjustment_description): """Set adjustment description. Args: adjustment_description(str): Adjustment description. """ self.adjustment_description = adjustment_description def get_adjustment_description(self): """Get adjustment description. Returns: str: Adjustment description. """ return self.adjustment_description def set_sub_total(self, sub_total): """Set sub total. Args: sub_total(float): Sub total. """ self.sub_total = sub_total def get_sub_total(self): """Get sub total. Returns: float: Sub total. """ return self.sub_total def set_total(self, total): """Set total. Args: total(float): Total. """ self.total = total def get_total(self): """Get total. Returns: float: Total. """ return self.total def set_price_precision(self, price_precision): """Set price precision. Args: price_precision(int): Price precision. """ self.price_precision = price_precision def get_price_precision(self): """Get price precision. Returns: int: Price precision. """ return self.price_precision def set_taxes(self, tax): """Set taxes. Args: taxes(instance): Tax object. """ self.taxes.extend(tax) def get_taxes(self): """Get taxes. Returns: list of instance: List of tax object. """ return self.taxes def set_billing_address(self, address): """Set billing address. Args: address(instance): Address object. """ self.billing_address = address def get_billing_address(self): """Get billing address. Returns: instance: Address object. """ return self.billing_address def set_shipping_address(self, address): """Set shipping address. Args: address(instance): Address object. """ self.shipping_address = address def get_shipping_address(self): """Get shipping address. Returns: instance: Address object. """ return self.shipping_address def set_notes(self, notes): """Set note. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_terms(self, terms): """Set terms. Args: terms(str): Terms. """ self.terms = terms def get_terms(self): """Get terms. Returns: str: Terms. """ return self.terms def set_custom_fields(self, custom_field): """Set custom fields. Args: custom_field(instance): Custom field. """ self.custom_fields.append(custom_field) def get_custom_fields(self): """Get custom field. Returns: list of instance: List of custom field object. """ return self.custom_fields def set_template_id(self, template_id): """Set template id. Args: template_id(str): Template id. """ self.template_id = template_id def get_template_id(self): """Get template id. Returns: str: Template id. """ return self.template_id def set_template_name(self, template_name): """Set template name. Args: template_name(str): Template name. """ self.template_name = template_name def get_template_name(self): """Get template name. Returns: str: Template name. """ return self.template_name def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time. Args: last_modified_time(str): Last modified time. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time. Returns: str: LAst modified time. """ return self.last_modified_time def set_salesperson_id(self, salesperson_id): """Set salesperson id. Args: salesperson_id(str): Salesperson id. """ self.salesperson_id = salesperson_id def get_salesperson_id(self): """Get salesperson id. Returns: str: Salesperson id. """ return self.salesperson_id def set_salesperson_name(self, salesperson_name): """Set salesperson_name. Args: salesperson_name(str): Salesperson name. """ self.salesperson_name = salesperson_name def get_salesperson_name(self): """Get salesperson name. Returns: str: Salesperson name. """ return self.salesperson_name def set_accepted_date(self, accepted_date): """Set accepted date. Args: accepted_date(str): Accepted date. """ self.accepted_date = accepted_date def get_accepted_date(self): """Get accepted date. Returns: str: Accepted date. """ return self.accepted_date def set_declined_date(self, declined_date): """Set declined date. Args: declined_date(str): Declined date. """ self.declined_date = declined_date def get_declined_date(self): """Get declined date. Returns: str: Declined date. """ return self.declined_date def set_tax_total(self, tax_total): """Set tax total. Args: tax_total(float): Tax total. """ self.tax_total = tax_total def get_tax_total(self): """Get tax total. Returns: float: Tax total. """ return self.tax_total def to_json(self): """This method is used to comnvert estimates object to json object. Returns: dict: Dictionary containing json object for estimates. """ data = {} if self.customer_id != '': data['customer_id'] = self.customer_id if self.estimate_number != '': data['estimate_number'] = self.estimate_number if self.contact_persons: data['contact_persons'] = self.contact_persons if self.template_id != '': data['template_id'] = self.template_id if self.reference_number != '': data['reference_number'] = self.reference_number if self.date != '': data['date'] = self.date if self.expiry_date != '': data['expiry_date'] = self.expiry_date if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.discount > 0: data['discount'] = self.discount if self.is_discount_before_tax is not None: data['is_discount_before_tax'] = self.is_discount_before_tax if self.discount_type != '': data['discount_type'] = self.discount_type if self.salesperson_name != '': data['salesperson_name'] = self.salesperson_name if self.custom_fields: data['custom_fields'] = [] for value in self.custom_fields: custom_field = value.to_json() data['custom_fields'].append(custom_field) if self.line_items: data['line_items'] = [] for value in self.line_items: line_item = value.to_json() data['line_items'].append(line_item) if self.notes != '': data['notes'] = self.notes if self.terms != '': data['terms'] = self.terms if self.shipping_charge > 0: data['shipping_charge'] = self.shipping_charge if self.adjustment != '': data['adjustment'] = self.adjustment if self.adjustment_description != '': data['adjustment_description'] = self.adjustment_description return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Estimate.py", "copies": "1", "size": "16768", "license": "mit", "hash": 4114108447654552600, "line_mean": 20.9189542484, "line_max": 76, "alpha_frac": 0.5243916985, "autogenerated": false, "ratio": 4.372359843546284, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.020307806694587212, "num_lines": 765 }
#$Id$ from books.model.Address import Address class Organization: """This class is used to create object for organization.""" def __init__(self): """Initialize parameters for organization object. """ self.organization_id = '' self.name = '' self.is_default_org = None self.account_created_date = '' self.time_zone = '' self.language_code = '' self.date_format = '' self.field_separator = '' self.fiscal_year_start_month = '' self.contact_name = '' self.industry_type = '' self.industry_size = '' self.company_id_label = '' self.company_id_value = '' self.tax_id_label = '' self.tax_id_value = '' self.currency_id = '' self.currency_code = '' self.currency_symbol = '' self.currency_format = '' self.price_precision = 0 self.address = Address() self.org_address = '' self.remit_to_address = '' self.phone = '' self.fax = '' self.website = '' self.email = '' self.tax_basis = '' self.is_org_active = None self.name = '' self.value = '' self.version = '' self.plan_type = 0 self.plane_name = '' self.plan_period = '' self.tax_group_enabled = None self.account_created_date_formatted = "" self.zi_migration_status = 0 self.user_role = '' self.custom_fields = [] self.is_new_customer_custom_fields = None self.is_portal_enabled = None self.portal_name = '' self.tax_type = '' def set_organization_id(self, organization_id): """Set organization id. Args: organization_id(str): Organization id. """ self.organization_id = organization_id def get_organization_id(self): """Get organization id. Returns: str: Organization id. """ return self.organization_id def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def set_is_default_org(self, is_default_org): """Set whether it is default organization. Args: is_default_org(bool): True if it is default organization else false. """ self.is_default_org = is_default_org def get_is_default_org(self): """Get whether it is default organization. Returns: bool: True if it is default organization else false. """ return self.is_default_org def set_account_created_date(self, account_created_date): """Set account created date. Args: account_created_date(str): Account created date. """ self.account_created_date = account_created_date def get_account_created_date(self): """Get account created date. Returns: str: Account created date. """ return self.account_created_date def set_time_zone(self, time_zone): """Set time zone. Args: time_zone(str): Time zone. """ self.time_zone = time_zone def get_time_zone(self): """Get time zone. Returns: str: Time zone. """ return self.time_zone def set_language_code(self, language_code): """Set language code. Args: language_code(str): Language code. """ self.language_code = language_code def get_language_code(self): """Get language code. Returns: str: Language code. """ return self.language_code def set_date_format(self, date_format): """Set date format. Args: date_format(str): Date format. """ self.date_format = date_format def get_date_format(self): """Get date format. Returns: str: Date format. """ return self.date_format def set_field_separator(self, field_separator): """Set field separator. Args: field_separator(str): Field separator. """ self.field_separator = field_separator def get_field_separator(self): """Get field separator. Returns: str: Field separator. """ return self.field_separator def set_fiscal_year_start_month(self, fiscal_year_start_month): """Set fiscal year field separator. Args: fiscal_year_start_month(str): Fiscal year start month. """ self.fiscal_year_start_month = fiscal_year_start_month def get_fiscal_year_start_month(self): """Get fiscal year start month. Returns: str: Fiscal year start month. """ return self.fiscal_year_start_month def set_contact_name(self, contact_name): """Set contact name. Args: contact_name(str): Contact name. """ self.contact_name = contact_name def get_contact_name(self): """Get contact name. Returns: str: Contact name. """ return self.contact_name def set_industry_type(self, industry_type): """Set industry type. Args: industry_type(str): Industry type. """ self.industry_type = industry_type def get_industry_type(self): """Get industry type. Returns: str: Industry type. """ return self.industry_type def set_industry_size(self, industry_size): """Set industry size. Args: industry_size(str): Industry size. """ self.industry_size = industry_size def get_industry_size(self): """Get industry size. Returns: str: Industry size. """ return self.industry_size def set_company_id_label(self, company_id_label): """Set company id label. Args: company_id_label(str): Company id label. """ self.company_id_label = company_id_label def get_company_id_label(self): """Get company id label. Returns: str: Company id label. """ return self.company_id_label def set_company_id_value(self, company_id_value): """Set company id value. Args: company_id_value(str): Company id value. """ self.company_id_value = company_id_value def get_company_id_value(self): """Get company id value. Returns: str: Company id value. """ return self.company_id_value def set_tax_id_label(self, tax_id_label): """Set tax id label. Args: tax_id_label(str): Tax id label. """ self.tax_id_label = tax_id_label def get_tax_id_label(self): """Get tax id label. Retruns: str: Tax id label. """ return self.tax_id_label def set_tax_id_value(self, tax_id_value): """Set tax id value. Args: tax_id_value(str): Tax id value. """ self.tax_id_value = tax_id_value def get_tax_id_value(self): """Get atx id value. Returns: str: Tax id value. """ return self.tax_id_value def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code. Returns: str: Currency code. """ return self.currency_code def set_currency_symbol(self, currency_symbol): """Set currency symbol. Args: currency_symbol(str): Currency symbol. """ self.currency_symbol = currency_symbol def get_currency_symbol(self): """Get currency symbol. Returns: str: Currency symbol. """ return self.currency_symbol def set_currency_format(self, currency_format): """Set currency format. Args: currency_format(str): Currency format. """ self.currency_format = currency_format def get_currency_format(self): """Get currency format. Retruns: str: Currency format. """ return self.currency_format def set_price_precision(self, price_precision): """Set price precision. Args: price_precision(int): Price precision. """ self.price_precision = price_precision def set_address(self, address): """Set address. Args: address(instance): Address """ self.address = address def get_address(self): """Get address. Returns: instance: Address. """ return self.address def set_org_address(self, org_address): """Set organization address. Args: org_address(str): Organization address. """ self.org_address = org_address def get_org_address(self): """Get organization address. Returns: str: Organization address. """ return self.org_address def set_remit_to_address(self, remit_to_address): """Set remit to address. Args: remit_to_address(str): Remit to address. """ self.remit_to_address = remit_to_address def get_remit_to_address(self): """Get remit to address. Returns: str: Remit to address. """ return self.remit_to_address def set_phone(self, phone): """Set phone. Args: phone(str): Phone. """ self.phone = phone def get_phone(self): """Get phone. Returns: str: Phone. """ return self.phone def set_fax(self, fax): """Set fax. Args: fax(str): Fax. """ self.fax = fax def get_fax(self): """Get fax. Returns: str: Fax. """ return self.fax def set_website(self, website): """Set website. Args: website(str): Website. """ self.website = website def set_email(self, email): """Set email. Args: email(str): Email. """ self.email = email def get_email(self): """Get email. Returns: str: Email. """ return self.email def set_tax_basis(self, tax_basis): """Set tax basis. Args: tax_basis(str): Tax basis. """ self.tax_basis = tax_basis def get_tax_basis(self): """Get tax basis. Returns: str: Tax basis. """ return self.tax_basis def set_is_org_active(self, is_org_active): """Set whether it the organization is active or not. Args: is_org_active(bool): True if organization is active else false. """ self.is_org_active = is_org_active def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_value(self, value): """Set value. Args: value(str): Value. """ self.value = value def get_value(self): """Get value. Returns: str: Value. """ return self.value def set_version(self, version): """Set version. Args: version(str): Version """ self.version = version def get_version(self): """Get version. Returns: str: Version. """ return self.version def set_plan_type(self, plan_type): """Set plan type. Args: plan_type(int): Plan type. """ self.plan_type = plan_type def get_plan_type(self): """Get plan type. Returns: int: Plan type. """ return self.plan_type def set_plan_name(self, plan_name): """Set plan name. Args: plan_name(str): Plan name. """ self.plan_name = plan_name def get_plan_name(self): """Get plan name. Args: str: Plan name. """ return self.plan_name def set_plan_period(self, plan_period): """Set plan period. Args: plan_period(str): Plan period. """ self.plan_period = plan_period def get_plan_period(self): """Get plan period. Returns: str: Plan period. """ return self.plan_period def set_tax_group_enabled(self, tax_group_enabled): """Set tax group enabled. Args: tax_group_enabled(bool): Tax group enabled. """ self.tax_group_enabled = tax_group_enabled def get_tax_group_enabled(self): """Get tax group enabled. Returns: bool: Tax group enabled. """ return self.tax_group_enabled def set_account_created_date_formatted(self, account_created_date_formatted): """Set account created date formatted. Args: account_created_date_formatted(str): Account created date formatted. """ self.account_created_date_formatted = account_created_date_formatted def get_account_created_date_formatted(self): """Get account created date formatted. Returns: str: Account created date formatted. """ return self.account_created_date_formatted def set_zi_migration_status(self, zi_migration_status): """Set zi migration status. Args: zi_migration_status(int): Zi migration status. """ self.zi_migration_status = zi_migration_status def get_zi_migration_status(self): """Get zi migration status . Returns: int: Zi migration status. """ return self.zi_migration_status def set_custom_fields(self, custom_field): """Set custom fields. Args: custom_field(instance): Custom field. """ self.custom_fields.append(custom_field) def get_custom_fields(self): """Get custom fields. Returns: list of instance: List of custom fields object. """ return self.custom_fields def set_user_role(self, user_role): """Set user role. Args: user_role(str): User role. """ self.user_role = user_role def get_user_role(self): """Get user role. Returns: str: User role. """ return self.user_role def set_is_new_customer_custom_fields(self, is_new_customer_custom_fields): """Set whether new customer custom fields or not. Args: is_new_customer_custom_fields(bool): True if new customer custom fields else False. """ self.is_new_customer_custom_fields = is_new_customer_custom_fields def get_is_new_customer_custom_fields(self): """Get whether new customer custom fields or not. Returns: bool: True if new customer custom fields else false. """ return self.is_new_customer_custom_fields def set_is_portal_enabled(self, is_portal_enabled): """Set whether portal is enabled or not. Args: is_portal_enabled(bool): True if portal enabled else false. """ self.is_portal_enabled = is_portal_enabled def get_is_portal_enabled(self): """Get whether is portal enabled. Returns: bool: True if portal is enabled else false. """ return self.is_portal_enabled def set_portal_name(self, portal_name): """Set portal name. Args: portal_name(str): Portal name. """ self.portal_name = portal_name def get_portal_name(self): """Get portal name. Returns: str: Portal name. """ return self.portal_name def set_tax_type(self, tax_type): """Set tax type. Args: tax_type(str): Tax type. """ self.tax_type = tax_type def get_tax_type(self): """Get tax type. Returns: str: Tax type. """ return self.tax_type def to_json(self): """This method is used to convert organizations object to json format. Returns: dict: Dictionary containing json object for organizations. """ data = {} if self.name != '': data['name'] = self.name if self.address is not None: data['address'] = self.address.to_json() if self.industry_type != '': data['industry_type'] = self.industry_type if self.industry_size != '': data['industry_size'] = self.industry_size if self.fiscal_year_start_month != '': data['fiscal_year_start_month'] = self.fiscal_year_start_month if self.currency_code != '': data['currency_code'] = self.currency_code if self.time_zone != '': data['time_zone'] = self.time_zone if self.date_format != '': data['date_format'] = self.date_format if self.field_separator != '': data['field_separator'] = self.field_separator if self.language_code != '': data['language_code'] = self.language_code if self.tax_basis != '': data['tax_basis'] = self.tax_basis if self.org_address != '': data['org_address'] = self.org_address if self.remit_to_address != '': data['remit_to_address'] = self.remit_to_address if self.tax_type != '': data['tax_type'] = self.tax_type return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Organization.py", "copies": "1", "size": "18783", "license": "mit", "hash": -2722121004196364300, "line_mean": 20.7144508671, "line_max": 95, "alpha_frac": 0.5244636107, "autogenerated": false, "ratio": 4.129947229551451, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002374624078447796, "num_lines": 865 }
#$Id$ from books.model.Address import Address class RecurringInvoice: """This class is used to creat object for Recurring invoice.""" def __init__(self): """Initialize parameters for Recurring invoice object.""" self.recurrence_name = '' self.customer_id = '' self.contact_persons = [] self.template_id = '' self.start_date = '' self.end_date = '' self.recurrence_frequency = '' self.repeat_every = 0 self.payment_terms = 0 self.payment_terms_label = '' self.exchange_rate = 0.0 self.payment_options = { 'payment_gateways': [] } self.discount = '' self.is_discount_before_tax = '' self.discount_type = '' self.line_items = [] self.salesperson_name = '' self.shipping_charge = 0.0 self.adjustment = 0.0 self.adjustment_description = '' self.notes = '' self.terms = '' self.recurring_invoice_id = '' self.status = '' self.total = 0.0 self.customer_name = '' self.last_sent_date = '' self.next_invoice_date = '' self.created_time = '' self.last_modified_time = '' self.currency_id = '' self.price_precision = 0 self.currency_code = '' self.currency_symbol = '' self.late_fee = {} self.sub_total = 0.0 self.tax_total = 0.0 self.allow_partial_payments = None self.taxes = [] self.billing_address = Address() self.shipping_address = Address() self.template_name = '' self.salesperson_id = '' self.custom_fields = [] def set_custom_fields(self, custom_fields): """Set custom fields. Args: custom_fields(list): List of custom fields. """ self.custom_fields.extend(custom_fields) def get_custom_fields(self): """Get custom fields. Returns: list: List of custom fields. """ return self.custom_fields def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_recurrence_name(self, recurrence_name): """Set name of the recurring invoice. Args: recurrence_name(str): Name of the recurring invoice. """ self.recurrence_name = recurrence_name def get_recurrence_name(self): """Get name of the recurring invoice. Returns: str: Name of the recurring invoice.. """ return self.recurrence_name def set_customer_id(self, customer_id): """Set ID for the customer for which recurring invoice has been created. Args: customer_id(str): Customer id for which recurring invoice has been created. """ self.customer_id = customer_id def get_customer_id(self): """Get ID for the customer for which recurring invoice has been created. Returns: str: Customer id for which recurring invoice has been created. """ return self.customer_id def set_contact_persons(self, contact_persons): """Set Contact persons associated with the recurring invoice. Args: contact_persons(list): List of contact persons id. """ self.contact_persons.extend(contact_persons) def get_contact_persons(self): """Get contact persons associated with the recurring invoice. Returns: list: List of contact persons id. """ return self.contact_persons def set_template_id(self, template_id): """Set ID of the pdf template associated with the recurring profile. Args: template_id(str): Template id. """ self.template_id = template_id def get_template_id(self): """Get ID of the pdf template associated with the recurring profile. Returns: str: Template id. """ return self.template_id def set_start_date(self, start_date): """Set start date for the recurring invoice. Args: start_date(str): Starting date of the recurring invoice. """ self.start_date = start_date def get_start_date(self): """Get start date of the recurring invoice. Returns: str: Starting date of the recurring invoice. """ return self.start_date def set_end_date(self, end_date): """Set the date at which the recurring invoice has to be expires. Args: end_date(str): Date on which recurring invoice expires. """ self.end_date = end_date def get_end_date(self): """Get the date at which the recurring invoice has to be expires. Returns: str: Date on which recurring invoice expires. """ return self.end_date def set_recurrence_frequency(self, recurrence_frequency): """Set the frequency for the recurring invoice. Args: recurrence_frequency(str): Frequency for the recurring invoice. Allowed values re days, weeks, months and years. """ self.recurrence_frequency = recurrence_frequency def get_recurrence_frequency(self): """Get the frequency of the recurring invoice. Returns: str: Frequency of the recurring invoice. """ return self.recurrence_frequency def set_repeat_every(self, repeat_every): """Set frequency to repeat. Args: repeat_every(int): Frequency to repeat. """ self.repeat_every = repeat_every def get_repeat_every(self): """Get frequency to repeat. Returns: int: Frequency to repeat. """ return self.repeat_every def set_payment_terms(self, payment_terms): """Set payment terms in days. Invoice due date will be calculated based on this. Args: payment_terms(int): Payment terms in days.Example 15, 30, 60. """ self.payment_terms = payment_terms def get_payment_terms(self): """Get payment terms. Returns: int: Payment terms in days. """ return self.payment_terms def set_payment_terms_label(self, payment_terms_label): """Set payment terms label. Args: payment_terms_label(str): Payment terms label. Default value for 15 days is "Net 15". """ self.payment_terms_label = payment_terms_label def get_payment_terms_label(self): """Get payment terms label. Returns: str: Payment terms label. """ return self.payment_terms_label def set_exchange_rate(self, exchange_rate): """Set exchange rate for the currency. Args: exchange_rate(float): Exchange rate for currency. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate of the currency. Returns: float: Exchange rate of the currency. """ return self.exchange_rate def set_payment_options(self, payment_gateways): """Set payment options associated with the recurring invoice, online payment gateways. Args: payment_gateways(instance): Online payment gateway through which payment can be made. """ self.payment_options['payment_gateways'].append(payment_gateways) def get_payment_options(self): """Get payment options associated with the recurring invoice, online payment gateways. Returns: dict: Payment options details. """ return self.payment_options def set_discount(self, discount): """Set discount applied to the invoice. Args: discount(str): Discount applied to the invoice. It can be either in % or in amount. """ self.discount = discount def get_discount(self): """Get discount applied to the invoice. Returns: str: Discount applied to the invoice. """ return self.discount def set_is_discount_before_tax(self, is_discount_before_tax): """Set whether to discount before tax. Args: is_discount_before_tax(bool): True to discount befroe tax else False. """ self.is_discount_before_tax = is_discount_before_tax def get_is_discount_before_tax(self): """Get whether to discount before tax. Returns: bool: True to discount before tax else False. """ return self.is_discount_before_tax def set_discount_type(self, discount_type): """Set how the discount is specified. Args: discount_type(str): Discount type. Allowed values are entity_level and item_level. """ self.discount_type = discount_type def get_discount_type(self): """Get discount type. Returns: str: Discount type. """ return self.discount_type def set_line_items(self, line_item): """Set line items for an invoice. Args: line_items(instance): Line items object. """ self.line_items.append(line_item) def get_line_items(self): """Get line items of an invoice. Returns: list: List of line items instance. """ return self.line_items def set_salesperson_name(self, salesperson_name): """Set name of the salesperson. Args: salesperson_name(str): Salesperson name. """ self.salesperson_name = salesperson_name def get_salesperson_name(self): """Get salesperson name. Returns: str: Salesperson name. """ return self.salesperson_name def set_shipping_charge(self, shipping_charge): """Set shipping charges applied to the invoice. Args: shipping_charge(float): Shipping charges applied to the invoice. """ self.shipping_charge = shipping_charge def get_shipping_charge(self): """Get shipping charges applied to invoice. Returns: float: Shipping charges applied to the invoice. """ return self.shipping_charge def set_adjustment(self, adjustment): """Set adjustments made to the invoice. Args: adjustment(float): Adjustments made to the invoice. """ self.adjustment = adjustment def get_adjustment(self): """Get adjustments made to the invoice. Returns: float: Adjustments made to the invoice. """ return self.adjustment def set_adjustment_description(self, adjustment_description): """Set the adjustment description. Args: adjustment_description(str): Adjustment description. """ self.adjustment_description = adjustment_description def get_adjustment_description(self): """Get adjustment description. Returns: str: Adjustment description. """ return self.adjustment_description def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_terms(self, terms): """Set terms. Args: terms(str): Terms. """ self.terms = terms def get_terms(self): """Get terms. Returns: str: Terms. """ return self.terms def set_recurring_invoice_id(self, recurring_invoice_id): """Set recurring invoice id. Args: recurring_invoice_id(str): Recurring invoice id. """ self.recurring_invoice_id = recurring_invoice_id def get_recurring_invoice_id(self): """Get recurring invoice id. Returns: str: Recurring invoice id. """ return self.recurring_invoice_id def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_total(self, total): """Set total. Args: total(float): Total. """ self.total = total def get_total(self): """Get total. Returns: float: Total. """ return self.total def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_last_sent_date(self, last_sent_date): """Set last sent date. Args: last_sent_date(str): Last sent date. """ self.last_sent_date = last_sent_date def get_last_sent_date(self): """Get last sent date. Returns: str: Last sent date. """ return self.last_sent_date def set_next_invoice_date(self, next_invoice_date): """Set next invoice date. Args: next_invoice_date(str): Next invoice date. """ self.next_invoice_date = next_invoice_date def get_next_invoice_date(self): """Get next invoice date. Returns: str: Next invoice date. """ return self.next_invoice_date def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time. Args: last_modified_time(str): Last modified time. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time. Returns: str: Last modified time. """ return self.last_modified_time def set_price_precision(self, price_precision): """Set price precision. Args: price_precision(int): Price precision. """ self.price_precision = price_precision def get_price_precision(self): """Get price precision. Returns: int: Price precision. """ return self.price_precision def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code. Returns: str: Currency code. """ return self.currency_code def set_currency_symbol(self, currency_symbol): """Set currency symbol. Args: currency_symbol(str): Currency symbol. """ self.currency_symbol = currency_symbol def get_currency_symbol(self): """Get currency symbol. Returns: str: Currency symbol. """ return self.currency_symbol def set_late_fee(self, late_fee): """Set late fee. Args: late_fee(dict): Late fee. """ self.late_fee = late_fee def get_late_fee(self): """Get late fee. Returns: dict: LAte fee. """ return self.late_fee def set_sub_total(self, sub_total): """Set sub total. Args: sub_total(float): Sub total. """ self.sub_total = sub_total def get_sub_total(self): """Get sub total. Returns: float: Sub total. """ return self.sub_total def set_tax_total(self, tax_total): """Set tax total. Args: tax_total(float): Tax total. """ self.tax_total = tax_total def get_tax_total(self): """Get tax total. Returns: float: Tax total. """ return self.tax_total def set_allow_partial_payments(self, allow_partial_payments): """Set whether to allow partial payments or not. Args: allow_partial_payments(bool): True to allow partial payments. """ self.allow_partial_payments = allow_partial_payments def get_allow_partial_payments(self): """Get whether partial payments are allowed or not. Returns: str: True if partial payments are allowed else False. """ return self.allow_partial_payments def set_taxes(self, taxes): """Set taxes. Args: taxes(instance): Tax object. """ self.taxes.append(taxes) def get_taxes(self): """Get taxes. Returns: list: List of taxes object. """ return self.taxes def set_billing_address(self, address): """Set billing address. Args: address(instance): Address object. """ self.billing_address = (address) def get_billing_address(self): """Get billing address. Returns: instance: Billing address object. """ return self.billing_address def set_shipping_address(self, address): """Set shipping address. Args: address(instance): Shipping address. """ self.shipping_address = address def get_shipping_address(slef): """Get shipping address. Returns: instance: Shipping address object. """ return self.shipping_address def set_template_name(self, template_name): """Set template name. Args: template_name(str): Template name. """ self.template_name = template_name def get_template_name(self): """Get template name. Returns: str: Template name. """ return self.template_name def set_salesperson_id(self, salesperson_id): """Set salesperson id. Args: salesperson_id(str): Salesperson id. """ self.salesperson_id = salesperson_id def get_salesperson_id(self): """Get salesperson id. Returns: str: Salesperson id. """ return self.salesperson_id def to_json(self): """This method is used to convert recurring invoice object to json object. Returns: dict: Dictionary containing json object for recurring invoice. """ data = {} if self.recurrence_name != '': data['recurrence_name'] = self.recurrence_name if self.customer_id != '': data['customer_id'] = self.customer_id if self.contact_persons: data['contact_persons'] = self.contact_persons if self.template_id != '': data['template_id'] = self.template_id if self.start_date != '': data['start_date'] = self.start_date if self.end_date != '': data['end_date'] = self.end_date if self.recurrence_frequency != '': data['recurrence_frequency'] = self.recurrence_frequency if self.repeat_every != '': data['repeat_every'] = self.repeat_every if self.payment_terms != '': data['payment_terms'] = self.payment_terms if self.payment_terms_label != '': data['payment_terms_label'] = self.payment_terms_label if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.payment_options['payment_gateways']: data['payment_options'] = { 'payment_gateways': [] } for value in self.payment_options['payment_gateways']: data['payment_options']['payment_gateways'].append(\ value.to_json()) if self.discount > 0: data['discount'] = self.discount if self.is_discount_before_tax is not None: data['is_discount_before_tax'] = self.is_discount_before_tax if self.discount_type != '': data['discount_type'] = self.discount_type if self.line_items: data['line_items'] = [] for value in self.line_items: line_item = value.to_json() data['line_items'].append(line_item) if self.notes != '': data['notes'] = self.notes if self.terms != '': data['terms'] = self.terms if self.salesperson_name != '': data['salesperson_name'] = self.salesperson_name if self.shipping_charge > 0: data['shipping_charge'] = self.shipping_charge if self.adjustment != '': data['adjustment'] = self.adjustment if self.adjustment_description != '': data['adjustment_description'] = self.adjustment_description return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/RecurringInvoice.py", "copies": "1", "size": "22336", "license": "mit", "hash": -3726584015379376600, "line_mean": 23.2782608696, "line_max": 82, "alpha_frac": 0.5462034384, "autogenerated": false, "ratio": 4.410742496050553, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5456945934450552, "avg_score": null, "num_lines": null }
#$Id$# from books.model.BankAccount import BankAccount from books.model.BankAccountList import BankAccountList from books.model.Transaction import Transaction from books.model.Statement import Statement from books.model.PageContext import PageContext class BankAccountsParser: """This class is used to parse the json response for Bank accounts.""" def get_list(self, resp): """This method parses the given response and returns bank account list object. Args: resp(dict): Response containing json object for Bank account list. Returns: instance: Bank account list object. """ bank_account_list = BankAccountList() for value in resp['bankaccounts']: bank_accounts = BankAccount() bank_accounts.set_account_id(value['account_id']) bank_accounts.set_account_name(value['account_name']) bank_accounts.set_currency_id(value['currency_id']) bank_accounts.set_currency_code(value['currency_code']) bank_accounts.set_account_type(value['account_type']) bank_accounts.set_uncategorized_transactions(\ value['uncategorized_transactions']) bank_accounts.set_is_active(value['is_active']) bank_accounts.set_balance(value['balance']) bank_accounts.set_bank_name(value['bank_name']) bank_accounts.set_routing_number(value['routing_number']) bank_accounts.set_is_primary_account(value['is_primary_account']) bank_accounts.set_is_paypal_account(value['is_paypal_account']) if value['is_paypal_account']: bank_accounts.set_paypal_email_address(\ value['paypal_email_address']) bank_account_list.set_bank_accounts(bank_accounts) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) bank_account_list.set_page_context(page_context_obj) return bank_account_list def get_account_details(self, resp): """This method parses the given response and returns bank account object. Args: resp(dict): Response containing json object for bank accounts. Returns: instance: Bank accounts object. Raises: Books Exception: If status is not '200' or '201'. """ bank_account = resp['bankaccount'] bank_account_obj = BankAccount() bank_account_obj.set_account_id(bank_account['account_id']) bank_account_obj.set_account_name(bank_account['account_name']) bank_account_obj.set_currency_id(bank_account['currency_id']) bank_account_obj.set_currency_code(bank_account['currency_code']) bank_account_obj.set_account_type(bank_account['account_type']) bank_account_obj.set_account_number(bank_account['account_number']) bank_account_obj.set_uncategorized_transactions(\ bank_account['uncategorized_transactions']) bank_account_obj.set_is_active(bank_account['is_active']) bank_account_obj.set_balance(bank_account['balance']) bank_account_obj.set_bank_name(bank_account['bank_name']) bank_account_obj.set_routing_number(bank_account['routing_number']) bank_account_obj.set_is_primary_account(bank_account[\ 'is_primary_account']) bank_account_obj.set_is_paypal_account(bank_account[\ 'is_paypal_account']) if bank_account['is_paypal_account']: bank_account_obj.set_paypal_email_address(\ bank_account['paypal_email_address']) bank_account_obj.set_description(bank_account['description']) return bank_account_obj def get_message(self, resp): """This message parses the given response and returns message string. Args: resp(dict): Response containing json object for message. Returns: str: Success message. """ return resp['message'] def get_statement(self, resp): """This method parses the given response and returns statement object. Args: resp(dict): Response containing json onbject for statement. Returns: instance: Statement object. """ statement = resp['statement'] statement_obj = Statement() statement_obj.set_statement_id(statement['statement_id']) statement_obj.set_from_date(statement['from_date']) statement_obj.set_to_date(statement['to_date']) statement_obj.set_source(statement['source']) for value in statement['transactions']: transactions = Transaction() transactions.set_transaction_id(value['transaction_id']) transactions.set_debit_or_credit(value['debit_or_credit']) transactions.set_date(value['date']) transactions.set_customer_id(value['customer_id']) transactions.set_payee(value['payee']) transactions.set_reference_number(value['reference_number']) transactions.set_amount(value['amount']) transactions.set_status(value['status']) statement_obj.set_transactions(transactions) page_context = resp['page_context'] page_context_obj = PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) statement_obj.set_page_context(page_context_obj) return statement_obj
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/BankAccountsParser.py", "copies": "1", "size": "6244", "license": "mit", "hash": -7724259800207564000, "line_mean": 42.9718309859, "line_max": 79, "alpha_frac": 0.6410954516, "autogenerated": false, "ratio": 4.065104166666667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009426888571733705, "num_lines": 142 }
#$Id$# from books.model.BankRule import BankRule from books.model.BankRuleList import BankRuleList from books.model.Criteria import Criteria class BankRulesParser: """This class is used to parse the json response for Bank rules.""" def get_rules(self, resp): """This method parses the given response and returns list of bank rules object. Args: resp(dict): Dictionary containing json object for bank rules. Returns: list of instance: List of Bank rules object. """ bank_rules = BankRuleList() for value in resp['rules']: bank_rule = BankRule() bank_rule.set_rule_id(value['rule_id']) bank_rule.set_rule_name(value['rule_name']) bank_rule.set_rule_order(value['rule_order']) bank_rule.set_apply_to(value['apply_to']) bank_rule.set_criteria_type(value['criteria_type']) bank_rule.set_record_as(value['record_as']) bank_rule.set_account_id(value['account_id']) bank_rule.set_account_name(value['account_name']) for criteria_value in value['criterion']: criteria = Criteria() criteria.set_criteria_id(criteria_value['criteria_id']) criteria.set_field(criteria_value['field']) criteria.set_comparator(criteria_value['comparator']) criteria.set_value(criteria_value['value']) bank_rule.set_criterion(criteria) bank_rules.set_bank_rules(bank_rule) return bank_rules def get_rule(self, resp): """This method parses the given response and returns bank rule object. Args: resp(dict): Dictionary containing json object for bank rules. Returns: instance: Bank rules object. """ bank_rule = BankRule() rule = resp['rule'] bank_rule.set_rule_id(rule['rule_id']) bank_rule.set_rule_name(rule['rule_name']) bank_rule.set_rule_order(rule['rule_order']) bank_rule.set_apply_to(rule['apply_to']) bank_rule.set_criteria_type(rule['criteria_type']) bank_rule.set_record_as(rule['record_as']) for value in rule['criterion']: criteria = Criteria() criteria.set_criteria_id(value['criteria_id']) criteria.set_field(value['field']) criteria.set_comparator(value['comparator']) criteria.set_value(value['value']) bank_rule.set_criterion(criteria) bank_rule.set_account_id(rule['account_id']) bank_rule.set_account_name(rule['account_name']) bank_rule.set_tax_id(rule['tax_id']) bank_rule.set_customer_id(rule['customer_id']) bank_rule.set_customer_name(rule['customer_name']) bank_rule.set_reference_number(rule['reference_number']) return bank_rule def get_message(self, resp): """This method parses the given response and returns message string. Args: resp(dict): Dictionary containing json object for message. Returns: str: Success message. """ return resp['message']
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/BankRulesParser.py", "copies": "1", "size": "3224", "license": "mit", "hash": 7865440182043323000, "line_mean": 36.488372093, "line_max": 78, "alpha_frac": 0.598325062, "autogenerated": false, "ratio": 4.040100250626566, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5138425312626567, "avg_score": null, "num_lines": null }
#$Id$# from books.model.BankRule import BankRule from books.model.Criteria import Criteria from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") bank_rules_api = zoho_books.get_bank_rules_api() accounts_api = zoho_books.get_bank_accounts_api() account_id = accounts_api.get_bank_accounts().get_bank_accounts()[0].get_account_id() target_account_id = accounts_api.get_bank_accounts().get_bank_accounts()[1].get_account_id() rule_id = bank_rules_api.get_rules(account_id).get_bank_rules()[0].get_rule_id() contact_api = zoho_books.get_contacts_api() customer_id = contact_api.get_contacts().get_contacts()[0].get_contact_id() # get rules list print bank_rules_api.get_rules(account_id) # get a rule print bank_rules_api.get(rule_id) #create a rule rule=BankRule() rule.set_rule_name('rule 9') rule.set_target_account_id(target_account_id) rule.set_apply_to('deposits') rule.set_criteria_type('and') criteria = Criteria() criteria.set_field('payee') criteria.set_comparator('is') criteria.set_value('dfd') rule.set_criterion(criteria) rule.set_record_as('sales_without_invoices') rule.set_account_id(account_id) rule.set_tax_id('') rule.set_reference_number('from_statement') rule.set_customer_id(customer_id) print bank_rules_api.create(rule) # update a rule rule=BankRule() rule.set_rule_name('rule 8') rule.set_target_account_id(target_account_id) rule.set_apply_to('deposits') rule.set_criteria_type('and') criteria = Criteria() criteria.set_field('payee') criteria.set_comparator('is') criteria.set_value('dfd') rule.set_criterion(criteria) rule.set_record_as('sales_without_invoices') rule.set_account_id(account_id) rule.set_tax_id('') rule.set_reference_number('from_statement') rule.set_customer_id(customer_id) print bank_rules_api.update(rule_id,rule) # Delete a rule print bank_rules_api.delete(rule_id)
{ "repo_name": "zoho/books-python-wrappers", "path": "test/BankRuleTest.py", "copies": "1", "size": "1883", "license": "mit", "hash": -3170692998511449600, "line_mean": 25.9, "line_max": 92, "alpha_frac": 0.7477429634, "autogenerated": false, "ratio": 2.7250361794500724, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.8873274885171896, "avg_score": 0.019900851535635235, "num_lines": 70 }
#$Id$# from books.model.BaseCurrencyAdjustment import BaseCurrencyAdjustment from books.model.BaseCurrencyAdjustmentList import BaseCurrencyAdjustmentList from books.model.PageContext import PageContext from books.model.Account import Account class BaseCurrencyAdjustmentParser: """This class is used to parse the json object for Base Currency adjustment Api.""" def get_list(self, resp): """This method parses the given response and returns base currency adjustment list object. Args: resp(dict): Response containing json for base currency adjustments list. Returns: instance: Base currency list object. """ base_currency_adjustment_list = BaseCurrencyAdjustmentList() for value in resp['base_currency_adjustments']: base_currency_adjustment = BaseCurrencyAdjustment() base_currency_adjustment.set_base_currency_adjustment_id(\ value['base_currency_adjustment_id']) base_currency_adjustment.set_adjustment_date(value[\ 'adjustment_date']) base_currency_adjustment.set_exchange_rate(value['exchange_rate']) base_currency_adjustment.set_currency_id(value['currency_id']) base_currency_adjustment.set_currency_code(value['currency_code']) base_currency_adjustment.set_notes(value['notes']) base_currency_adjustment.set_gain_or_loss(value['gain_or_loss']) base_currency_adjustment_list.set_base_currency_adjustments(\ base_currency_adjustment) page_context = resp['page_context'] page_context_obj = PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) base_currency_adjustment_list.set_page_context(page_context_obj) return base_currency_adjustment_list def get_base_currency_adjustment(self, resp): """This method parses the given response and returns the base currency adjustment details object. Args: resp(dict): Response containing json object for base currency adjustment. Returns: instance: Base currency adjustment object. """ data = resp['data'] base_currency_adjustment = BaseCurrencyAdjustment() base_currency_adjustment.set_base_currency_adjustment_id(data[\ 'base_currency_adjustment_id']) base_currency_adjustment.set_currency_id(data['currency_id']) base_currency_adjustment.set_currency_code(data['currency_code']) base_currency_adjustment.set_adjustment_date(data['adjustment_date']) base_currency_adjustment.set_exchange_rate(data['exchange_rate']) base_currency_adjustment.set_notes(data['notes']) for value in data['accounts']: account = Account() account.set_account_id(value['account_id']) account.set_account_name(value['account_name']) account.set_bcy_balance(value['bcy_balance']) account.set_fcy_balance(value['fcy_balance']) account.set_adjusted_balance(value['adjusted_balance']) account.set_gain_or_loss(value['gain_or_loss']) account.set_gl_specific_type(value['gl_specific_type']) base_currency_adjustment.set_accounts(account) return base_currency_adjustment def list_account_details(self, resp): """This method parses the given response and returns list of account details for base currency adjustment. Args: resp(dict): Response containing json object for account details list. Returns: instance: Base currency adjustment object. """ data = resp['data'] base_currency_adjustment = BaseCurrencyAdjustment() base_currency_adjustment.set_adjustment_date(data['adjustment_date']) base_currency_adjustment.set_adjustment_date_formatted(data[\ 'adjustment_date_formatted']) base_currency_adjustment.set_exchange_rate(data['exchange_rate']) base_currency_adjustment.set_exchange_rate_formatted(data[\ 'exchange_rate_formatted']) base_currency_adjustment.set_currency_id(data['currency_id']) for value in data['accounts']: accounts = Account() accounts.set_account_id(value['account_id']) accounts.set_account_name(value['account_name']) accounts.set_gl_specific_type(value['gl_specific_type']) accounts.set_fcy_balance(value['fcy_balance']) accounts.set_fcy_balance_formatted(value['fcy_balance_formatted']) accounts.set_bcy_balance(value['bcy_balance']) accounts.set_bcy_balance_formatted(value['bcy_balance_formatted']) accounts.set_adjusted_balance(value['adjusted_balance']) accounts.set_adjusted_balance_formatted(value[\ 'adjusted_balance_formatted']) accounts.set_gain_or_loss(value['gain_or_loss']) accounts.set_gain_or_loss_formatted(value['gain_or_loss_formatted']) base_currency_adjustment.set_accounts(accounts) base_currency_adjustment.set_notes(data['notes']) base_currency_adjustment.set_currency_code(data['currency_code']) return base_currency_adjustment def get_message(self, resp): """This method parses the given response and returns message. Args: resp(dict): Response containing json object for message. Returns: str: Success message. """ return resp['message']
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/BaseCurrencyAdjustmentParser.py", "copies": "1", "size": "6061", "license": "mit", "hash": 5662737706913062000, "line_mean": 44.9166666667, "line_max": 81, "alpha_frac": 0.6543474674, "autogenerated": false, "ratio": 4.277346506704305, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004815808063448129, "num_lines": 132 }
#$Id$# from books.model.BaseCurrencyAdjustment import BaseCurrencyAdjustment from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") base_currency_adjustment_api = zoho_books.get_base_currency_adjustment_api() base_currency_adjustment_id = base_currency_adjustment_api.get_base_currency_adjustments().get_base_currency_adjustments()[0].get_base_currency_adjustment_id() #List base currency adjustment parameter = { 'filter_by': 'Date.All', 'sort_column': 'adjustment_date'} print base_currency_adjustment_api.get_base_currency_adjustments() print base_currency_adjustment_api.get_base_currency_adjustments(parameter) #Get a base currency adjustment print base_currency_adjustment_api.get(base_currency_adjustment_id) # List account details for base currency adjustments settings_api = zoho_books.get_settings_api() currency_id = settings_api.get_currencies().get_currencies()[0].get_currency_id() parameter = {'currency_id': currency_id, 'adjustment_date': '2014-04-21', 'exchange_rate': 20.0, 'notes': 'sdfs'} print base_currency_adjustment_api.list_account_details(parameter) # Create a base currency adjustment account_ids = '71127000000000367' base_currency_adjustment = BaseCurrencyAdjustment() base_currency_adjustment.set_currency_id('71127000000000105') base_currency_adjustment.set_adjustment_date('2014-04-21') base_currency_adjustment.set_exchange_rate(20.0) base_currency_adjustment.set_notes('hello') print base_currency_adjustment_api.create(base_currency_adjustment, account_ids) #Delete a base currency adjustment print base_currency_adjustment_api.delete(base_currency_adjustment_id)
{ "repo_name": "zoho/books-python-wrappers", "path": "test/BaseCurrencyAdjustmentTest.py", "copies": "1", "size": "1732", "license": "mit", "hash": -2798251469080187000, "line_mean": 36.652173913, "line_max": 159, "alpha_frac": 0.7609699769, "autogenerated": false, "ratio": 3.409448818897638, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9518753734221617, "avg_score": 0.030333012315204244, "num_lines": 46 }
#$Id$# from books.model.Bill import Bill from books.model.BillList import BillList from books.model.LineItem import LineItem from books.model.Address import Address from books.model.Tax import Tax from books.model.BillPayment import BillPayment from books.model.PageContext import PageContext from books.model.Comment import Comment from books.model.CommentList import CommentList class BillsParser: """This class is used to parse the json for Bills""" def get_list(self, resp): """This method parses the given response and returns bill list object. Args: resp(dict): Response containing json object for bill list. Returns: instance: Bill list object. """ bill_list = BillList() for value in resp['bills']: bill = Bill() bill.set_bill_id(value['bill_id']) bill.set_vendor_id(value['vendor_id']) bill.set_vendor_name(value['vendor_name']) bill.set_status(value['status']) bill.set_bill_number(value['bill_number']) bill.set_reference_number(value['reference_number']) bill.set_date(value['date']) bill.set_due_date(value['due_date']) bill.set_due_days(value['due_days']) bill.set_currency_id(value['currency_id']) bill.set_currency_code(value['currency_code']) bill.set_total(value['total']) bill.set_balance(value['balance']) bill.set_created_time(value['created_time']) bill_list.set_bills(bill) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) bill_list.set_page_context(page_context_obj) return bill_list def get_bill(self, resp): """This method parses the given response and returns bills object. Args: resp(dict): Response containing json object for bill object. Returns: instance: Bill object. """ bill = resp['bill'] bill_obj = Bill() bill_obj.set_bill_id(bill['bill_id']) bill_obj.set_vendor_id(bill['vendor_id']) bill_obj.set_vendor_name(bill['vendor_name']) bill_obj.set_unused_credits_payable_amount(bill[\ 'unused_credits_payable_amount']) bill_obj.set_status(bill['status']) bill_obj.set_bill_number(bill['bill_number']) bill_obj.set_date(bill['date']) bill_obj.set_due_date(bill['due_date']) bill_obj.set_reference_number(bill['reference_number']) bill_obj.set_due_by_days(bill['due_by_days']) bill_obj.set_due_in_days(bill['due_in_days']) bill_obj.set_currency_id(bill['currency_id']) bill_obj.set_currency_code(bill['currency_code']) bill_obj.set_currency_symbol(bill['currency_symbol']) bill_obj.set_price_precision(bill['price_precision']) bill_obj.set_exchange_rate(bill['exchange_rate']) for value in bill['line_items']: line_item = LineItem() line_item.set_line_item_id(value['line_item_id']) line_item.set_account_id(value['account_id']) line_item.set_account_name(value['account_name']) line_item.set_description(value['description']) line_item.set_bcy_rate(value['bcy_rate']) line_item.set_rate(value['rate']) line_item.set_quantity(value['quantity']) line_item.set_tax_id(value['tax_id']) line_item.set_tax_name(value['tax_name']) line_item.set_tax_type(value['tax_type']) line_item.set_tax_percentage(value['tax_percentage']) line_item.set_item_total(value['item_total']) line_item.set_item_order(value['item_order']) bill_obj.set_line_items(line_item) bill_obj.set_sub_total(bill['sub_total']) bill_obj.set_tax_total(bill['tax_total']) bill_obj.set_total(bill['total']) for value in bill['taxes']: tax = Tax() tax.set_tax_name(value['tax_name']) tax.set_tax_amount(value['tax_amount']) bill_obj.set_taxes(tax) bill_obj.set_payment_made(bill['payment_made']) bill_obj.set_balance(bill['balance']) billing_address = bill['billing_address'] billing_address_obj = Address() billing_address_obj.set_address(billing_address['address']) billing_address_obj.set_city(billing_address['city']) billing_address_obj.set_state(billing_address['state']) billing_address_obj.set_zip(billing_address['zip']) billing_address_obj.set_country(billing_address['country']) billing_address_obj.set_fax(billing_address['fax']) bill_obj.set_billing_address(billing_address_obj) for value in bill['payments']: payments = BillPayment() payments.set_payment_id(value['payment_id']) payments.set_bill_id(value['bill_id']) payments.set_bill_payment_id(value['bill_payment_id']) payments.set_payment_mode(value['payment_mode']) payments.set_description(value['description']) payments.set_date(value['date']) payments.set_reference_number(value['reference_number']) payments.set_exchange_rate(value['exchange_rate']) payments.set_amount(value['amount']) payments.set_paid_through_account_id(value[\ 'paid_through_account_id']) payments.set_paid_through_account_name(value[\ 'paid_through_account_name']) payments.set_is_single_bill_payment(value[\ 'is_single_bill_payment']) billing_address_obj.set_payments(payments) bill_obj.set_created_time(bill['created_time']) bill_obj.set_last_modified_time(bill['last_modified_time']) bill_obj.set_reference_id(bill['reference_id']) bill_obj.set_notes(bill['notes']) bill_obj.set_terms(bill['terms']) bill_obj.set_attachment_name(bill['attachment_name']) return bill_obj def get_message(self, resp): """This method parses the given response and returns string message. Args: resp(dict): Response containing json object for success message. Returns: str: Success message. """ return resp['message'] def get_payments_list(self, resp): """This method parses the given response and returns payments list object. Args: resp(dict): Response containing json object for payments list. Returns: list of instance: List of payments object. """ payments = [] for value in resp['payments']: payment = BillPayment() payment.set_payment_id(value['payment_id']) payment.set_bill_id(value['bill_id']) payment.set_bill_payment_id(value['bill_payment_id']) payment.set_vendor_id(value['vendor_id']) payment.set_vendor_name(value['vendor_name']) payment.set_payment_mode(value['payment_mode']) payment.set_description(value['description']) payment.set_date(value['date']) payment.set_reference_number(value['reference_number']) payment.set_exchange_rate(value['exchange_rate']) payment.set_amount(value['amount']) payment.set_paid_through(value['paid_through']) payment.set_is_single_bill_payment(value['is_single_bill_payment']) payments.append(payment) return payments def get_comments(self, resp): comments = CommentList() for value in resp['comments']: comment = Comment() comment.set_comment_id(value['comment_id']) comment.set_bill_id(value['bill_id']) comment.set_description(value['description']) comment.set_commented_by_id(value['commented_by_id']) comment.set_commented_by(value['commented_by']) comment.set_comment_type(value['comment_type']) comment.set_date(value['date']) comment.set_date_description(value['date_description']) comment.set_time(value['time']) comment.set_operation_type(value['operation_type']) comment.set_transaction_id(value['transaction_id']) comment.set_transaction_type(value['transaction_type']) comments.set_comments(comment) return comments def get_comment(self, resp): comment = resp['comment'] comment_obj = Comment() comment_obj.set_comment_id(comment['comment_id']) comment_obj.set_bill_id(comment['bill_id']) comment_obj.set_description(comment['description']) comment_obj.set_commented_by_id(comment['commented_by_id']) comment_obj.set_commented_by(comment['commented_by']) comment_obj.set_comment_type(comment['comment_type']) comment_obj.set_date(comment['date']) comment_obj.set_date_description(comment['date_description']) comment_obj.set_time(comment['time']) comment_obj.set_comment_type(comment['comment_type']) return comment_obj
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/BillsParser.py", "copies": "1", "size": "9722", "license": "mit", "hash": 2533266326336532000, "line_mean": 42.9909502262, "line_max": 79, "alpha_frac": 0.6128368648, "autogenerated": false, "ratio": 3.693768996960486, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48066058617604857, "avg_score": null, "num_lines": null }
#$Id$# from books.model.Bill import Bill from books.model.LineItem import LineItem from books.model.Address import Address from books.model.PaymentAndCredit import PaymentAndCredit from books.model.BillPayment import BillPayment from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") bill_api = zoho_books.get_bills_api() bill_id = bill_api.get_bills().get_bills()[1].get_bill_id() vendor_api = zoho_books.get_vendor_payments_api() vendor_id = vendor_api.get_vendor_payments().get_vendor_payments()[0].get_vendor_id() param = {'filter_by': 'AccountType.Expense'} chart_of_accounts_api = zoho_books.get_chart_of_accounts_api() account_id = chart_of_accounts_api.get_chart_of_accounts(param).get_chartofaccounts()[1].get_account_id() attachment = '/{file_directory}/emp.pdf' # List bills parameter = {'status':'open'} print bill_api.get_bills() print bill_api.get_bills(parameter) # Get a bill print bill_api.get(bill_id) # Create a bill bill = Bill() bill.set_vendor_id(vendor_id) bill.set_bill_number('38') bill.set_date('2014-05-12') bill.set_due_date('2014-05-13') bill.set_exchange_rate(1) bill.set_reference_number("2") line_items = LineItem() line_items.set_account_id(account_id) line_items.set_description('table') line_items.set_rate("1000.0") line_items.set_quantity("4") line_items.set_item_order("0") bill.set_line_items(line_items) bill.set_notes("before due") bill.set_terms('conditions Apply') print bill_api.create(bill) #print bill_api.create(bill,attachment) # Update a bill bill = Bill() bill.set_vendor_id(vendor_id) bill.set_bill_number('38') bill.set_date('2014-05-12') bill.set_due_date('2014-05-13') bill.set_exchange_rate(1) bill.set_reference_number("2") line_items = LineItem() line_items.set_account_id(account_id) line_items.set_description('table') line_items.set_rate("1000.0") line_items.set_quantity("4") line_items.set_tax_id("") line_items.set_item_order("0") bill.set_line_items(line_items) bill.set_notes("before due") bill.set_terms('conditions Apply') #print bill_api.update(bill_id,bill) print bill_api.update(bill_id,bill,attachment) # Delete a bill print bill_api.delete(bill_id) # Void a bill print bill_api.void_a_bill(bill_id) # Mark a bill as open print bill_api.mark_a_bill_as_open(bill_id) # Update billing_ address billing_address=Address() billing_address.set_address('no. 2 kumaran streeet') billing_address.set_city('chennai') billing_address.set_state('Tamilnadu') billing_address.set_zip('908') billing_address.set_country('India') print bill_api.update_billing_address(bill_id,billing_address) ''' ''' param = {'status': 'paid'} bill_id = bill_api.get_bills(param).get_bills()[0].get_bill_id() payment_id = bill_api.list_bill_payments(bill_id)[0].get_payment_id() bill_payment_id = bill_api.list_bill_payments(bill_id)[0].get_bill_payment_id() # List bill payment print bill_api.list_bill_payments(bill_id) # Apply credits bill_payments = BillPayment() bill_payments.set_payment_id(payment_id) bill_payments.set_amount_applied(0.0) print bill_api.apply_credits(bill_id,[bill_payments]) # Delete a payment print bill_api.delete_a_payment(bill_id,bill_payment_id) ''' # Get a bill attachment ''' print bill_api.get_a_bill_attachment(bill_id) #print bill_api.get_a_bill_attachment("71127000000080017",True) # Add attachment to a bill attachment='/{file_directory}/download.jpg' print bill_api.add_attachments_to_a_bill(bill_id,attachment) # Delete an attachment print bill_api.delete_an_attachment(bill_id) # List bill comments and history comment_id = bill_api.list_bill_comments_and_history(bill_id).get_comments()[0].get_comment_id() print bill_api.list_bill_comments_and_history(bill_id) # Add Comment description="Welcome" print bill_api.add_comment(bill_id,description) # Delete a comment comment_id = "71127000000204442" print bill_api.delete_a_comment(bill_id,comment_id)
{ "repo_name": "zoho/books-python-wrappers", "path": "test/BillTest.py", "copies": "1", "size": "3928", "license": "mit", "hash": -8091498114454983000, "line_mean": 24.6732026144, "line_max": 105, "alpha_frac": 0.7436354379, "autogenerated": false, "ratio": 2.6594448205822614, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.3903080258482261, "avg_score": null, "num_lines": null }
#$Id$# from books.model.ChartOfAccount import ChartOfAccount from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") chart_of_accounts_api = zoho_books.get_chart_of_accounts_api() account_id = chart_of_accounts_api.get_chart_of_accounts().get_chartofaccounts()[0].get_account_id() # list chart of accounts parameters = {'filter_by':'AccountType.Active'} print chart_of_accounts_api.get_chart_of_accounts() print chart_of_accounts_api.get_chart_of_accounts(parameters) # Get an Account print chart_of_accounts_api.get(account_id) # Create an account account = ChartOfAccount() account.set_account_name('DD1') account.set_account_type('other_asset') account.set_currency_id('') account.set_description('Fixed Deposit') print chart_of_accounts_api.create(account) # Update an account account = ChartOfAccount() account.set_account_name('SD1') account.set_account_type('other_asset') #account.set_currency_id('') account.set_description('Fixed Deposit') print chart_of_accounts_api.update("71127000000165001", account) #Delete an account print chart_of_accounts_api.delete(account_id) #Mark an account as active print chart_of_accounts_api.mark_an_account_as_active(account_id) # Mark an account as inactive print chart_of_accounts_api.mark_an_account_as_inactive(account_id) # List of transactions for an account #account_id = param = {'amount.less_than':100.0, #'account_id':account_id, 'filter_by':'TransactionType.Invoice'} print chart_of_accounts_api.list_of_transactions() print chart_of_accounts_api.list_of_transactions(param).get_transactions() # Delete a transaction transaction_id = chart_of_accounts_api.list_of_transactions(param).get_transactions()[0].get_transaction_id() print chart_of_accounts_api.delete_a_transaction("71127000000165001")
{ "repo_name": "zoho/books-python-wrappers", "path": "test/ChartOfAccountsTest.py", "copies": "1", "size": "1845", "license": "mit", "hash": 5006151708270715000, "line_mean": 26.5373134328, "line_max": 109, "alpha_frac": 0.7609756098, "autogenerated": false, "ratio": 3.0852842809364547, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43462598907364547, "avg_score": null, "num_lines": null }
#$Id$# from books.model.Contact import Contact from books.model.Email import Email from books.model.Address import Address from books.model.ContactPerson import ContactPerson from books.model.ContactPersonList import ContactPersonList from books.model.CustomField import CustomField from books.model.DefaultTemplate import DefaultTemplate from books.model.PageContext import PageContext from books.model.ContactList import ContactList from books.model.ToContact import ToContact from books.model.FromEmail import FromEmail from books.model.CommentList import CommentList from books.model.Comment import Comment from books.model.CreditNoteRefundList import CreditNoteRefundList from books.model.CreditNoteRefund import CreditNoteRefund class ContactParser: """This class is used to parse the json for contact.""" def get_contact(self, resp): """This method parses the given response and creates a contact object. Args: resp(dict): Response containing json object for contact. Returns: instance: Contact object. """ contact = Contact() response = resp['contact'] contact.set_contact_id(response['contact_id']) contact.set_contact_name(response['contact_name']) contact.set_company_name(response['company_name']) contact.set_contact_salutation(response['contact_salutation']) contact.set_price_precision(response['price_precision']) contact.set_has_transaction(response['has_transaction']) contact.set_contact_type(response['contact_type']) contact.set_is_crm_customer(response['is_crm_customer']) contact.set_primary_contact_id(response['primary_contact_id']) contact.set_payment_terms(response['payment_terms']) contact.set_payment_terms_label(response['payment_terms_label']) contact.set_currency_id(response['currency_id']) contact.set_currency_code(response['currency_code']) contact.set_currency_symbol(response['currency_symbol']) contact.set_outstanding_receivable_amount(response[\ 'outstanding_receivable_amount']) contact.set_outstanding_receivable_amount_bcy(response[\ 'outstanding_receivable_amount_bcy']) contact.set_outstanding_payable_amount(response[\ 'outstanding_payable_amount']) contact.set_outstanding_payable_amount_bcy(response[\ 'outstanding_payable_amount_bcy']) contact.set_unused_credits_receivable_amount(response[\ 'unused_credits_receivable_amount']) contact.set_unused_credits_receivable_amount_bcy(response[\ 'unused_credits_receivable_amount_bcy']) contact.set_unused_credits_payable_amount(response[\ 'unused_credits_payable_amount']) contact.set_unused_credits_payable_amount_bcy(response[\ 'unused_credits_payable_amount_bcy']) contact.set_status(response['status']) contact.set_payment_reminder_enabled(response[\ 'payment_reminder_enabled']) for value in response['custom_fields']: custom_field = CustomField() custom_field.set_index(value['index']) custom_field.set_value(value['value']) custom_field.set_label(value['label']) contact_person.set_custom_fields(custom_field) billing_address = Address() billing_address.set_address(response['billing_address']['address']) billing_address.set_city(response['billing_address']['city']) billing_address.set_state(response['billing_address']['state']) billing_address.set_zip(response['billing_address']['zip']) billing_address.set_country(response['billing_address']['country']) billing_address.set_fax(response['billing_address']['fax']) contact.set_billing_address(billing_address) shipping_address = Address() shipping_address.set_address(response['shipping_address']['address']) shipping_address.set_city(response['shipping_address']['city']) shipping_address.set_state(response['shipping_address']['state']) shipping_address.set_zip(response['shipping_address']['zip']) shipping_address.set_country(response['shipping_address']['country']) shipping_address.set_fax(response['shipping_address']['fax']) contact.set_shipping_address(shipping_address) contact_persons = [] for value in response['contact_persons']: contact_person = ContactPerson() contact_person.set_contact_person_id(value['contact_person_id']) contact_person.set_salutation(value['salutation']) contact_person.set_first_name(value['first_name']) contact_person.set_last_name(value['last_name']) contact_person.set_email(value['email']) contact_person.set_phone(value['phone']) contact_person.set_mobile(value['mobile']) contact_person.set_is_primary_contact(value['is_primary_contact']) contact_persons.append(contact_person) contact.set_contact_persons(contact_persons) default_templates = DefaultTemplate() default_templates.set_invoice_template_id(response[ 'default_templates']['invoice_template_id']) default_templates.set_invoice_template_name(response[\ 'default_templates']['invoice_template_name']) default_templates.set_estimate_template_id(response[\ 'default_templates']['estimate_template_id']) default_templates.set_estimate_template_name(response[\ 'default_templates']['estimate_template_name']) default_templates.set_creditnote_template_id(response[\ 'default_templates']['creditnote_template_id']) default_templates.set_creditnote_template_name(response[\ 'default_templates']['creditnote_template_name']) default_templates.set_invoice_email_template_id(response[\ 'default_templates']['invoice_email_template_id']) default_templates.set_invoice_email_template_name(response[\ 'default_templates']['invoice_email_template_name']) default_templates.set_estimate_email_template_id(response[\ 'default_templates']['estimate_email_template_id']) default_templates.set_estimate_email_template_name(response[\ 'default_templates']['estimate_email_template_name']) default_templates.set_creditnote_email_template_id(response[\ 'default_templates']['creditnote_email_template_id']) default_templates.set_creditnote_email_template_name(response[\ 'default_templates']['creditnote_email_template_name']) contact.set_default_templates(default_templates) contact.set_notes(response['notes']) contact.set_created_time(response['created_time']) contact.set_last_modified_time(response['last_modified_time']) return contact def get_contacts(self, resp): """This method parses the given response and creates a contact list object. Args: resp(dict): Response containing json object for contact list. Returns: instance: Contact list object. """ contacts_list = ContactList() response = resp['contacts'] for value in resp['contacts']: contact = Contact() contact.set_contact_id(value['contact_id']) contact.set_contact_name(value['contact_name']) contact.set_company_name(value['company_name']) contact.set_contact_type(value['contact_type']) contact.set_status(value['status']) contact.set_payment_terms(value['payment_terms']) contact.set_payment_terms_label(value['payment_terms_label']) contact.set_currency_id(value['currency_id']) contact.set_currency_code(value['currency_code']) contact.set_outstanding_receivable_amount(value[\ 'outstanding_receivable_amount']) contact.set_outstanding_payable_amount(value[\ 'outstanding_payable_amount']) contact.set_unused_credits_receivable_amount(value[\ 'unused_credits_receivable_amount']) contact.set_unused_credits_payable_amount(value[\ 'unused_credits_payable_amount']) contact.set_first_name(value['first_name']) contact.set_last_name(value['last_name']) contact.set_email(value['email']) contact.set_phone(value['phone']) contact.set_mobile(value['mobile']) contact.set_created_time(value['created_time']) contact.set_last_modified_time(value['last_modified_time']) contacts_list.set_contacts(contact) page_context_object = PageContext() page_context = resp['page_context'] page_context_object.set_page(page_context['page']) page_context_object.set_per_page(page_context['per_page']) page_context_object.set_has_more_page(page_context['has_more_page']) page_context_object.set_applied_filter(page_context['applied_filter']) page_context_object.set_sort_column(page_context['sort_column']) page_context_object.set_sort_order(page_context['sort_order']) contacts_list.set_page_context(page_context_object) return contacts_list def get_contact_person(self, resp): """This method parses the given response and creates a contact person object. Args: resp(dict): Response containing json object for contact person. Returns: instance: Contact person object. """ contact_person = ContactPerson() response = resp['contact_person'] contact_person.set_contact_id(response['contact_id']) contact_person.set_contact_person_id(response['contact_person_id']) contact_person.set_salutation(response['salutation']) contact_person.set_first_name(response['first_name']) contact_person.set_last_name(response['last_name']) contact_person.set_email(response['email']) contact_person.set_phone(response['phone']) contact_person.set_mobile(response['mobile']) contact_person.set_is_primary_contact(response['is_primary_contact']) return contact_person def get_contact_persons(self, response): """This method parses the given repsonse and creates contact persons list object. Args: response(dict): Response containing json object for contact persons list. Returns: instance: Contact person list object. """ resp = response['contact_persons'] contact_person_list = ContactPersonList() for value in resp: contact_person = ContactPerson() contact_person.set_contact_person_id(value['contact_person_id']) contact_person.set_salutation(value['salutation']) contact_person.set_first_name(value['first_name']) contact_person.set_last_name(value['last_name']) contact_person.set_email(value['email']) contact_person.set_phone(value['phone']) contact_person.set_mobile(value['mobile']) contact_person.set_is_primary_contact(value['is_primary_contact']) contact_person_list.set_contact_persons(contact_person) page_context_object = PageContext() page_context = response['page_context'] page_context_object.set_page(page_context['page']) page_context_object.set_per_page(page_context['per_page']) page_context_object.set_has_more_page(page_context['has_more_page']) page_context_object.set_sort_column(page_context['sort_column']) page_context_object.set_sort_order(page_context['sort_order']) contact_person_list.set_page_context(page_context_object) return contact_person_list def get_message(self, response): """This method parses the given response and returns the message. Args: response(dict): Response containing json object. Returns: str: Success message. """ return response['message'] def get_mail_content(self, response): """This method parses the give response and creates object for email. Args: response(dict): Response containing json object for email . Returns: instance: Email object. """ email = Email() data = response['data'] email.set_body(data['body']) email.set_contact_id(data['contact_id']) email.set_subject(data['subject']) for to_contact in data['to_contacts']: to_contacts = ToContact() to_contacts.set_first_name(to_contact['first_name']) to_contacts.set_selected(to_contact['selected']) to_contacts.set_phone(to_contact['phone']) to_contacts.set_email(to_contact['email']) to_contacts.set_last_name(to_contact['last_name']) to_contacts.set_salutation(to_contact['salutation']) to_contacts.set_contact_person_id(to_contact['contact_person_id']) to_contacts.set_mobile(to_contact['mobile']) email.set_to_contacts(to_contacts) email.set_file_name(data['file_name']) for value in data['from_emails']: from_emails = FromEmail() from_emails.set_user_name(value['user_name']) from_emails.set_selected(value['selected']) from_emails.set_email(value['email']) from_emails.set_is_org_email_id(value['is_org_email_id']) email.set_from_emails(from_emails) return email def get_comment_list(self, response): """This method parses the given response and creates object for comments list. Args: response(dict): Response containing json object for comments list. Returns: instance: cComments list object. """ comment_list = CommentList() contact_comments = response['contact_comments'] for value in contact_comments: contact_comment = Comment() contact_comment.set_comment_id(value['comment_id']) contact_comment.set_contact_id(value['contact_id']) contact_comment.set_contact_name(value['contact_name']) contact_comment.set_description(value['description']) contact_comment.set_commented_by_id(value['commented_by_id']) contact_comment.set_commented_by(value['commented_by']) contact_comment.set_date(value['date']) contact_comment.set_date_description(value['date_description']) contact_comment.set_time(value['time']) contact_comment.set_transaction_id(value['transaction_id']) contact_comment.set_transaction_type(value['transaction_type']) contact_comment.set_is_entity_deleted(value['is_entity_deleted']) contact_comment.set_operation_type(value['operation_type']) comment_list.set_comments(contact_comment) page_context = response['page_context'] page_context_object = PageContext() page_context_object.set_page(page_context['page']) page_context_object.set_per_page(page_context['per_page']) page_context_object.set_has_more_page(page_context['has_more_page']) page_context_object.set_applied_filter(page_context['applied_filter']) page_context_object.set_sort_column(page_context['sort_column']) page_context_object.set_sort_order(page_context['sort_order']) comment_list.set_page_context(page_context_object) return comment_list def get_refund_list(self, response): """This method parses the given response and creates refund list object. Args: response(dict): Response containing json object for refund list. Returns: instance: Refund list object. """ list_refund = CreditNoteRefundList() creditnote_refunds = response['creditnote_refunds'] for value in creditnote_refunds: creditnote_refund = CreditNoteRefund() creditnote_refund.set_creditnote_refund_id(value[\ 'creditnote_refund_id']) creditnote_refund.set_creditnote_id(value['creditnote_id']) creditnote_refund.set_date(value['date']) creditnote_refund.set_refund_mode(value['refund_mode']) creditnote_refund.set_reference_number(value['reference_number']) creditnote_refund.set_creditnote_number(value['creditnote_number']) creditnote_refund.set_customer_name(value['customer_name']) creditnote_refund.set_description(value['description']) creditnote_refund.set_amount_bcy(value['amount_bcy']) creditnote_refund.set_amount_fcy(value['amount_fcy']) list_refund.set_creditnote_refunds(creditnote_refund) page_context = response['page_context'] page_context_object = PageContext() page_context_object.set_page(page_context['page']) page_context_object.set_per_page(page_context['per_page']) page_context_object.set_has_more_page(page_context['has_more_page']) page_context_object.set_report_name(page_context['report_name']) page_context_object.set_sort_column(page_context['sort_column']) page_context_object.set_sort_order(page_context['sort_order']) list_refund.set_page_context(page_context_object) return list_refund
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/ContactParser.py", "copies": "1", "size": "17874", "license": "mit", "hash": 4298390462533616000, "line_mean": 45.7905759162, "line_max": 82, "alpha_frac": 0.6464697326, "autogenerated": false, "ratio": 4.14517625231911, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.529164598491911, "avg_score": null, "num_lines": null }
#$Id$# from books.model.CreditNote import CreditNote from books.model.PageContext import PageContext from books.model.CreditNoteList import CreditNoteList from books.model.LineItem import LineItem from books.model.Address import Address from books.model.EmailHistory import EmailHistory from books.model.Email import Email from books.model.EmailTemplate import EmailTemplate from books.model.ToContact import ToContact from books.model.FromEmail import FromEmail from books.model.Template import Template from books.model.InvoiceCredited import InvoiceCredited from books.model.InvoiceCreditedList import InvoiceCreditedList from books.model.Invoice import Invoice from books.model.InvoiceList import InvoiceList from books.model.CreditNoteRefund import CreditNoteRefund from books.model.CreditNoteRefundList import CreditNoteRefundList from books.model.Comment import Comment from books.model.CommentList import CommentList class CreditNotesParser: """This class is used to parse the json for credit notes.""" def creditnotes_list(self,response): """This method parses the given response and creates a creditnotes list object. Args: response(dict):Response containing json object for credit notes list. Returns: instance: Creditnotes list object. """ credit_notes_list=CreditNoteList() credit_notes=[] for value in response['creditnotes']: credit_note=CreditNote() credit_note.set_creditnote_id(value['creditnote_id']) credit_note.set_creditnote_number(value['creditnote_number']) credit_note.set_status(value['status']) credit_note.set_reference_number(value['reference_number']) credit_note.set_date(value['date']) credit_note.set_total(value['total']) credit_note.set_balance(value['balance']) credit_note.set_customer_id(value['customer_id']) credit_note.set_customer_name(value['customer_name']) credit_note.set_currency_id(value['currency_id']) credit_note.set_currency_code(value['currency_code']) credit_note.set_created_time(value['created_time']) credit_note.set_last_modified_time(value['last_modified_time']) credit_note.set_is_emailed(value['is_emailed']) credit_notes.append(credit_note) credit_notes_list.set_creditnotes(credit_notes) page_context_obj=PageContext() page_context=response['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) credit_notes_list.set_page_context(page_context_obj) return credit_notes_list def get_creditnote(self,response): """This method parses the given response and returns credit note object. Args: response(dict): Response containing json object for credit note. Returns: instance: Credit note object. """ creditnote=response['creditnote'] credit_note=CreditNote() credit_note.set_creditnote_id(creditnote['creditnote_id']) credit_note.set_creditnote_number(creditnote['creditnote_number']) credit_note.set_date(creditnote['date']) credit_note.set_status(creditnote['status']) credit_note.set_reference_number(creditnote['reference_number']) credit_note.set_customer_id(creditnote['customer_id']) credit_note.set_customer_name(creditnote['customer_name']) credit_note.set_contact_persons(creditnote['contact_persons']) credit_note.set_currency_id(creditnote['currency_id']) credit_note.set_currency_code(creditnote['currency_code']) credit_note.set_exchange_rate(creditnote['exchange_rate']) credit_note.set_price_precision(creditnote['price_precision']) credit_note.set_template_id(creditnote['template_id']) credit_note.set_template_name(creditnote['template_name']) credit_note.set_is_emailed(creditnote['is_emailed']) for value in creditnote['line_items']: line_item=LineItem() line_item.set_item_id(value['item_id']) line_item.set_line_item_id(value['line_item_id']) line_item.set_account_id(value['account_id']) line_item.set_account_name(value['account_name']) line_item.set_name(value['name']) line_item.set_description(value['description']) line_item.set_item_order(value['item_order']) line_item.set_quantity(value['quantity']) line_item.set_unit(value['unit']) line_item.set_bcy_rate(value['bcy_rate']) line_item.set_rate(value['rate']) line_item.set_tax_id(value['tax_id']) line_item.set_tax_name(value['tax_name']) line_item.set_tax_type(value['tax_type']) line_item.set_tax_percentage(value['tax_percentage']) line_item.set_item_total(value['item_total']) credit_note.set_line_items(line_item) credit_note.set_sub_total(creditnote['sub_total']) credit_note.set_total(creditnote['total']) credit_note.set_total_credits_used(creditnote['total_credits_used']) credit_note.set_total_refunded_amount(\ creditnote['total_refunded_amount']) credit_note.set_balance(creditnote['balance']) taxes=[] for value in creditnote['taxes']: tax=Tax() tax.set_tax_name(value['tax_name']) tax.set_tax_amount(value['tax_amount']) taxes.append(tax) credit_note.set_taxes(taxes) billing_address=creditnote['billing_address'] billing_address_obj=Address() billing_address_obj.set_address(billing_address['address']) billing_address_obj.set_city(billing_address['city']) billing_address_obj.set_state(billing_address['state']) billing_address_obj.set_zip(billing_address['zip']) billing_address_obj.set_country(billing_address['country']) billing_address_obj.set_fax(billing_address['fax']) credit_note.set_billing_address(billing_address_obj) shipping_address=creditnote['shipping_address'] shipping_address_obj=Address() shipping_address_obj.set_address(shipping_address['address']) shipping_address_obj.set_city(shipping_address['city']) shipping_address_obj.set_state(shipping_address['state']) shipping_address_obj.set_zip(shipping_address['zip']) shipping_address_obj.set_country(shipping_address['country']) shipping_address_obj.set_fax(shipping_address['fax']) credit_note.set_shipping_address(shipping_address_obj) credit_note.set_created_time(creditnote['created_time']) credit_note.set_last_modified_time(creditnote['last_modified_time']) return credit_note def get_message(self,response): """This method parses the json object and returns string message. Args: response(dict): Response containing json object. Returns: str: Success message. """ return response['message'] def email_history(self,response): """This method parses the json object and returns list of email \ history object. Args: response(dict): Response containing json object for email history. Returns: list of instance: List of email history object. """ email_history=[] for value in response['email_history']: email_history_obj=EmailHistory() email_history_obj.set_mailhistory_id(value['mailhistory_id']) email_history_obj.set_from(value['from']) email_history_obj.set_to_mail_ids(value['to_mail_ids']) email_history_obj.set_subject(value['subject']) email_history_obj.set_date(value['date']) email_history_obj.set_type(value['type']) email_history.append(email_history_obj) return email_history def email(self,response): """This method parses the response and returns email object. Args: response(dict): Response containing json object for email. Returns: instance: Email object. """ data=response['data'] email=Email() email.set_body(data['body']) email.set_error_list(data['error_list']) email.set_subject(data['subject']) for value in data['emailtemplates']: email_template=EmailTemplate() email_template.set_selected(value['selected']) email_template.set_name(value['name']) email_template.set_email_template_id(value['email_template_id']) email.set_email_templates(email) for value in data['to_contacts']: to_contact=ToContact() to_contact.set_first_name(value['first_name']) to_contact.set_selected(value['selected']) to_contact.set_phone(value['phone']) to_contact.set_email(value['email']) to_contact.set_last_name(value['last_name']) to_contact.set_salutation(value['salutation']) to_contact.set_contact_person_id(value['contact_person_id']) to_contact.set_mobile(value['mobile']) email.set_to_contacts(to_contact) email.set_file_name(data['file_name']) email.set_file_name_without_extension(\ data['file_name_without_extension']) for value in data['from_emails']: from_email=FromEmail() from_email.set_user_name(value['user_name']) from_email.set_selected(value['selected']) from_email.set_email(value['email']) from_email.set_is_org_email_id(value['is_org_email_id']) email.set_from_emails(from_email) email.set_customer_id(data['customer_id']) return email def get_billing_address(self,response): """This method parses the response containing json object for billing address. Args: response(dict): Response containing json object for billing address. Returns: instance: Address object. """ billing_address=response['billing_address'] billing_address_obj=Address() billing_address_obj.set_address(billing_address['address']) billing_address_obj.set_city(billing_address['city']) billing_address_obj.set_state(billing_address['state']) billing_address_obj.set_zip(billing_address['zip']) billing_address_obj.set_country(billing_address['country']) billing_address_obj.set_fax(billing_address['fax']) billing_address_obj.set_is_update_customer(\ billing_address['is_update_customer']) return billing_address_obj def get_shipping_address(self,response): """This method parses the json object and returns shipping address \ object. Args: response(dict): Response containing json object for shipping \ address. Returns: instance: Shipping address object. """ shipping_address=response['shipping_address'] shipping_address_obj=Address() shipping_address_obj.set_address(shipping_address['address']) shipping_address_obj.set_city(shipping_address['city']) shipping_address_obj.set_state(shipping_address['state']) shipping_address_obj.set_zip(shipping_address['zip']) shipping_address_obj.set_country(shipping_address['country']) shipping_address_obj.set_fax(shipping_address['fax']) shipping_address_obj.set_is_update_customer(\ shipping_address['is_update_customer']) return shipping_address_obj def list_templates(self,response): """This method parses the json object and returns templates list. Args: response(dict): Response containing json object for templates list. Returns: lsit of instance: Lsit of templates object. """ templates=[] for value in response['templates']: template=Template() template.set_template_name(value['template_name']) template.set_template_id(value['template_id']) template.set_template_type(value['template_type']) templates.append(template) return templates def list_invoices_credited(self,response): """This method parses the json object and returns list of invoices credited. Args: response(dict): Response containing json object for invoices credited. Returns: instance: Invoices credited list object. """ invoices_credited = InvoiceCreditedList() for value in response['invoices_credited']: invoice_credited = InvoiceCredited() invoice_credited.set_creditnote_id(value['creditnote_id']) invoice_credited.set_invoice_id(value['invoice_id']) invoice_credited.set_creditnotes_invoice_id(\ value['creditnote_invoice_id']) invoice_credited.set_date(value['date']) invoice_credited.set_invoice_number(value['invoice_number']) invoice_credited.set_creditnotes_number(value['creditnote_number']) invoice_credited.set_credited_amount(value['credited_amount']) invoices_credited.set_invoices_credited(invoice_credited) return invoices_credited def credit_to_invoice(self,response): """This method parses the given response and returns invoices object. Args: response(dict): Responses containing json object for credit to invoice. Returns: instance: Invoice List object. """ invoices = InvoiceList() for value in response['apply_to_invoices']['invoices']: invoice=Invoice() invoice.set_invoice_id(value['invoice_id']) invoice.set_amount_applied(value['amount_applied']) invoices.set_invoices(invoice) return invoices def creditnote_refunds(self,response): """This method parses the given response and returns credit notes refund list. Args: response(dict): Repsonse containing json object for credit notes list. Returns: instance: Creditnote list object. """ creditnotes_refund_list=CreditNoteRefundList() for value in response['creditnote_refunds']: creditnotes_refund=CreditNoteRefund() creditnotes_refund.set_creditnote_refund_id(\ value['creditnote_refund_id']) creditnotes_refund.set_creditnote_id(value['creditnote_id']) creditnotes_refund.set_date(value['date']) creditnotes_refund.set_refund_mode(value['refund_mode']) creditnotes_refund.set_reference_number(value['reference_number']) creditnotes_refund.set_creditnote_number(\ value['creditnote_number']) creditnotes_refund.set_customer_name(value['customer_name']) creditnotes_refund.set_description(value['description']) creditnotes_refund.set_amount_bcy(value['amount_bcy']) creditnotes_refund.set_amount_fcy(value['amount_fcy']) creditnotes_refund_list.set_creditnote_refunds(creditnotes_refund) page_context=response['page_context'] page_context_obj=PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) creditnotes_refund_list.set_page_context(page_context_obj) return creditnotes_refund_list def get_creditnote_refund(self,response): """This method parses the given repsonse and returns credit note refund object. Args: response(dict): Response containing json object for credit note refund. Returns: isntacne: Credit note object. """ creditnote_refund=response['creditnote_refund'] creditnote_refund_obj=CreditNoteRefund() creditnote_refund_obj.set_creditnote_refund_id(\ creditnote_refund['creditnote_refund_id']) creditnote_refund_obj.set_creditnote_id(\ creditnote_refund['creditnote_id']) creditnote_refund_obj.set_date(creditnote_refund['date']) creditnote_refund_obj.set_refund_mode(creditnote_refund['refund_mode']) creditnote_refund_obj.set_reference_number(\ creditnote_refund['reference_number']) creditnote_refund_obj.set_amount(creditnote_refund['amount']) creditnote_refund_obj.set_exchange_rate(\ creditnote_refund['exchange_rate']) creditnote_refund_obj.set_from_account_id(\ creditnote_refund['from_account_id']) creditnote_refund_obj.set_from_account_name(\ creditnote_refund['from_account_name']) creditnote_refund_obj.set_description(creditnote_refund['description']) return creditnote_refund_obj def comments_list(self,response): """This method parses the given response and returns the comments list. Args: response(dict): Response containing json object for comments list. Returns: list of instance: List of comments object. """ comments_list = CommentList() for value in response['comments']: comment = Comment() comment.set_comment_id(value['comment_id']) comment.set_creditnote_id(value['creditnote_id']) comment.set_description(value['description']) comment.set_commented_by_id(value['commented_by_id']) comment.set_commented_by(value['commented_by']) comment.set_comment_type(value['comment_type']) comment.set_date(value['date']) comment.set_date_description(value['date_description']) comment.set_time(value['time']) comment.set_operation_type(value['operation_type']) comment.set_transaction_id(value['transaction_id']) comment.set_transaction_type(value['transaction_type']) comments_list.set_comments(comment) return comments_list def get_comment(self,response): """This method parses the given response and returns comments object. Args: response(dict): Response containing json object for comments. Returns: instance: Comments object. """ comment=response['comment'] comment_obj=Comment() comment_obj.set_comment_id(comment['comment_id']) comment_obj.set_creditnote_id(comment['creditnote_id']) comment_obj.set_description(comment['description']) comment_obj.set_commented_by_id(comment['commented_by_id']) comment_obj.set_commented_by(comment['commented_by']) comment_obj.set_date(comment['date']) return comment_obj
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/CreditNotesParser.py", "copies": "1", "size": "19942", "license": "mit", "hash": 7914787061184746000, "line_mean": 40.2024793388, "line_max": 80, "alpha_frac": 0.6392538361, "autogenerated": false, "ratio": 4.083128583128583, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.01273828970540211, "num_lines": 484 }
#$Id$# from books.model.CustomerPayment import CustomerPayment from books.model.CustomerPaymentList import CustomerPaymentList from books.model.PageContext import PageContext from books.model.Invoice import Invoice class CustomerPaymentsParser: """This class is used to parse the json for customer payments.""" def customer_payments(self,response): """This method parses the given response and returns customer payments list object. Args: response(dict): Response containing json object for customer payments list. Returns: instance: Customer payments list object. """ customer_payment_list=CustomerPaymentList() for value in response['customerpayments']: customer_payment=CustomerPayment() customer_payment.set_payment_id(value['payment_id']) customer_payment.set_payment_number(value['payment_number']) customer_payment.set_invoice_numbers(value['invoice_numbers']) customer_payment.set_date(value['date']) customer_payment.set_payment_mode(value['payment_mode']) customer_payment.set_amount(value['amount']) customer_payment.set_bcy_amount(value['bcy_amount']) customer_payment.set_unused_amount(value['unused_amount']) customer_payment.set_bcy_unused_amount(value['bcy_unused_amount']) customer_payment.set_account_id(value['account_id']) customer_payment.set_account_name(value['account_name']) customer_payment.set_description(value['description']) customer_payment.set_reference_number(value['reference_number']) customer_payment.set_customer_id(value['customer_id']) customer_payment.set_customer_name(value['customer_name']) customer_payment.set_created_time(value['created_time']) customer_payment.set_last_modified_time(\ value['last_modified_time']) customer_payment_list.set_customer_payments(customer_payment) page_context=response['page_context'] page_context_obj=PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) customer_payment_list.set_page_context(page_context_obj) return customer_payment_list def get_customer_payment(self,response): """This method parses the given response and returns customer payments object. Args: response(dict): Response containing json object for customer payments. Returns: instance: Customer payments object. """ payment=response['payment'] customer_payment=CustomerPayment() customer_payment.set_payment_id(payment['payment_id']) customer_payment.set_customer_id(payment['customer_id']) customer_payment.set_customer_name(payment['customer_name']) customer_payment.set_payment_mode(payment['payment_mode']) customer_payment.set_date(payment['date']) customer_payment.set_account_id(payment['account_id']) customer_payment.set_account_name(payment['account_name']) customer_payment.set_exchange_rate(payment['exchange_rate']) customer_payment.set_amount(payment['amount']) customer_payment.set_bank_charges(payment['bank_charges']) customer_payment.set_tax_account_id(payment['tax_account_id']) customer_payment.set_tax_account_name(payment['tax_account_name']) customer_payment.set_tax_amount_withheld(\ payment['tax_amount_withheld']) customer_payment.set_description(payment['description']) customer_payment.set_reference_number(payment['reference_number']) invoices=[] for value in payment['invoices']: invoice=Invoice() invoice.set_invoice_number(value['invoice_number']) invoice.set_invoice_payment_id(value['invoice_payment_id']) invoice.set_invoice_id(value['invoice_id']) invoice.set_amount_applied(value['amount_applied']) invoice.set_tax_amount_withheld(value['tax_amount_withheld']) invoice.set_total(value['total']) invoice.set_balance(value['balance']) invoice.set_date(value['date']) invoice.set_due_date(value['due_date']) invoices.append(invoice) customer_payment.set_invoices(invoices) return customer_payment def get_message(self,response): """This method parses the given response and returns the message. Args: response(dict): Response containing json object. Returns: str: Success message. """ return response['message']
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/CustomerPaymentsParser.py", "copies": "1", "size": "5238", "license": "mit", "hash": 5840719019720752000, "line_mean": 44.9473684211, "line_max": 79, "alpha_frac": 0.6489117984, "autogenerated": false, "ratio": 4.2759183673469385, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5424830165746939, "avg_score": null, "num_lines": null }
#$Id$# from books.model.CustomerPayment import CustomerPayment from books.model.Invoice import Invoice from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") customer_payments_api = zoho_books.get_customer_payments_api() payment_id = customer_payments_api.get_customer_payments().get_customer_payments()[0].get_payment_id() customer_id = customer_payments_api.get_customer_payments().get_customer_payments()[0].get_customer_id() invoice_api = zoho_books.get_invoices_api() invoice_id = invoice_api.get_invoices().get_invoices()[0].get_invoice_id() accounts_api = zoho_books.get_bank_accounts_api() account_id = accounts_api.get_bank_accounts().get_bank_accounts()[0].get_account_id() # List customer payments print customer_payments_api.get_customer_payments() # Get a customer payment print customer_payments_api.get(payment_id) # Create a payment_customer customer_payments = CustomerPayment() customer_payments.set_customer_id(customer_id) invoices = [] invoice = Invoice() invoice.set_invoice_id(invoice_id) invoice.set_amount_applied(20.0) invoice.set_tax_amount_withheld(4.0) invoices.append(invoice) customer_payments.set_invoices(invoices) customer_payments.set_payment_mode('Cash') customer_payments.set_description('') customer_payments.set_date('2014-01-01') customer_payments.set_reference_number('') customer_payments.set_exchange_rate(30.0) customer_payments.set_amount(300.0) customer_payments.set_bank_charges(4.0) customer_payments.set_tax_account_id('') customer_payments.set_account_id(account_id) print customer_payments_api.create(customer_payments) # Update a payment customer customer_payments = CustomerPayment() customer_payments.set_customer_id(customer_id) invoices = [] invoice = Invoice() invoice.set_invoice_id('71127000000121041') invoice.set_amount_applied(20.0) invoice.set_tax_amount_withheld(4.0) invoices.append(invoice) customer_payments.set_invoices(invoices) customer_payments.set_payment_mode('Cash') customer_payments.set_description('') customer_payments.set_date('2014-01-01') customer_payments.set_reference_number('') customer_payments.set_exchange_rate(30.0) customer_payments.set_amount(300.0) customer_payments.set_bank_charges(4.0) customer_payments.set_tax_account_id('') customer_payments.set_account_id('71127000000081061') print customer_payments_api.update(payment_id,customer_payments) # Delete a customer payment print customer_payments_api.delete(payment_id)
{ "repo_name": "zoho/books-python-wrappers", "path": "test/CustomerPaymentsTest.py", "copies": "1", "size": "2486", "license": "mit", "hash": -5364215794498684000, "line_mean": 31.2857142857, "line_max": 104, "alpha_frac": 0.7847948512, "autogenerated": false, "ratio": 3.1468354430379746, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.9354415864847949, "avg_score": 0.015442885878005057, "num_lines": 77 }
#$Id$# from books.model.Estimate import Estimate from books.model.Address import Address from books.model.Email import Email from books.model.ContactPerson import ContactPerson from books.model.LineItem import LineItem from books.model.CustomField import CustomField from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") estimate_api = zoho_books.get_estimates_api() estimate_id = estimate_api.get_estimates().get_estimates()[0].get_estimate_id() estimate_ids = estimate_api.get_estimates().get_estimates()[0].get_estimate_id() + ',' + estimate_api.get_estimates().get_estimates()[1].get_estimate_id() contact_api = zoho_books.get_contacts_api() customer_id = contact_api.get_contacts().get_contacts()[0].get_contact_id() items_api = zoho_books.get_items_api() item_id = items_api.list_items().get_items()[0].get_item_id() template_id = estimate_api.list_estimate_template().get_templates()[0].get_template_id() # to list Estimates print estimate_api.get_estimates() # to get an estimate #print estimate_api.get(estimate_id) #print estimate_api.get(estimate_id, True) #print estimate_api.get(estimate_id, False) #print estimate_api.get(estimate_id, True, 'json') print estimate_api.get(estimate_id, None, 'html') #to create an estimate ref_num = 'QRT-123456' date = '2013-10-03' expiry_date = '2013-10-17' exchange_rate = 1.0 discount = 0.0 discount_type = 'item_level' salesperson_name = 'Billu' name = 'at' description = 'building' estimate = Estimate() estimate.set_customer_id(customer_id) contact_person = [] estimate.set_contact_persons(contact_person) estimate.set_template_id(template_id) estimate.set_reference_number(ref_num) estimate.set_date(date) estimate.set_expiry_date(expiry_date) estimate.set_exchange_rate(exchange_rate) estimate.set_discount(discount) estimate.set_is_discount_before_tax(True) estimate.set_discount_type(discount_type) estimate.set_salesperson_name(salesperson_name) line_items = LineItem() line_items.set_item_id(item_id) line_items.set_name(name) line_items.set_description(description) estimate.set_line_items(line_items) line_items1 = LineItem() line_items1.set_item_id(item_id) line_items1.set_name('at') line_items1.set_description('build') estimate.set_line_items(line_items1) custom_field = CustomField() custom_field.set_index('') custom_field.set_value('custom') estimate.set_custom_fields(custom_field) estimate.set_notes('looking forward for your business') estimate.set_terms('terms and conditions apply') estimate.set_shipping_charge(0.0) estimate.set_adjustment(0.0) estimate.set_adjustment_description('Adjustment') #print estimate_api.create(estimate) #print estimate_api.create(estimate, False) #estimate.set_estimate_number('35') #print estimate_api.create(estimate, True, True) #print estimate_api.create(estimate, None, False) print estimate_api.create(estimate, True, None) # update an estimate ref_num = 'QRT-123456' date = '2013-10-03' expiry_date = '2013-10-17' exchange_rate = 1.0 discount = 0.0 discount_type = 'item_level' salesperson_name = 'Bob' name = 'at' description = 'building' estimate = Estimate() estimate.set_customer_id(customer_id) contact_person = [] estimate.set_contact_persons(contact_person) estimate.set_template_id(template_id) estimate.set_reference_number(ref_num) estimate.set_date(date) estimate.set_expiry_date(expiry_date) estimate.set_exchange_rate(exchange_rate) estimate.set_discount(discount) estimate.set_is_discount_before_tax(True) estimate.set_discount_type(discount_type) estimate.set_salesperson_name(salesperson_name) line_items = LineItem() line_items.set_item_id(item_id) line_items.set_name(name) line_items.set_description(description) estimate.set_line_items(line_items) line_items1 = LineItem() line_items1.set_item_id(item_id) line_items1.set_name('at') line_items1.set_description('build') estimate.set_line_items(line_items1) custom_field = CustomField() custom_field.set_index('') custom_field.set_value('custom') estimate.set_custom_fields(custom_field) estimate.set_notes('looking forward for your business') estimate.set_terms('terms and conditions apply') estimate.set_shipping_charge(0.0) estimate.set_adjustment(0.0) estimate.set_adjustment_description('Adjustment') #print estimate_api.update(estimate_id, estimate) print estimate_api.update(estimate_id, estimate, False) # delete an estimate print estimate_api.delete(estimate_id) # mark an estimate as sent print estimate_api.mark_an_estimate_as_sent(estimate_id) # mark an estimate as accepted print estimate_api.mark_an_estimate_as_accepted(estimate_id) # mark an estimate as declined print estimate_api.mark_an_estimate_as_declined(estimate_id) # email an estimate email = Email() to_mailid = ['example@gmail.com', 'example@zohocorp.com'] email.set_to_mail_ids(to_mailid) email.set_subject('Statement of transactions') email.set_body('welcome') print estimate_api.email_an_estimate(estimate_id, email) #email an estimate (attach a file) email = Email() to_mailid = ['example@gmail.com', 'example@zohocorp.com'] email.set_to_mail_ids(to_mailid) email.set_subject('Statement of transactions') email.set_body('welcome') email.set_file_name('new1.pdf') attachment = ['/{file_directory}/fil1.txt', '/{file_directory}/fil2.txt'] print estimate_api.email_an_estimate(estimate_id, email, attachment) # email estimates print estimate_api.email_estimates(estimate_ids) #check whether email success message has to be modelled! # Get estimate email content print estimate_api.get_estimate_email_content(estimate_id) print estimate_api.get_estimate_email_content(estimate_id, template_id) # Bulk export estimates print estimate_api.bulk_export_estimates(estimate_ids) #bulk print estimates print estimate_api.bulk_print_estimates(estimate_ids) #update billing address billing_address = Address() billing_address.set_address('43, Km street') billing_address.set_city('Chennai') billing_address.set_state('TamilNadu') billing_address.set_zip('3344') billing_address.set_country('India') billing_address.set_fax('67899') print estimate_api.update_billing_address(estimate_id, billing_address) print estimate_api.update_billing_address(estimate_id, billing_address, True) # update shipping address shipping_address = Address() shipping_address.set_address('43, Km street') shipping_address.set_city('Chennai') shipping_address.set_state('TamilNadu') shipping_address.set_zip('3344') shipping_address.set_country('India') shipping_address.set_fax('67899') print estimate_api.update_shipping_address(estimate_id, shipping_address) print estimate_api.update_shipping_address(estimate_id, shipping_address, False) #list estimate template print estimate_api.list_estimate_template() #update estimate template print estimate_api.update_estimate_template(estimate_id, template_id) #------------------------------------------------------------------------------------------------------------------------------------------ # Comments and history comment_id = estimate_api.list_comments_history(estimate_id).get_comments()[0].get_comment_id() #list estimate comments & history print estimate_api.list_comments_history(estimate_id) #Add Comment print estimate_api.add_comment(estimate_id, 'is description', True) # Update Comment print estimate_api.update_comment(estimate_id, comment_id, 'is a description', False) #delete Comment print estimate_api.delete_comment(estimate_id, comment_id)
{ "repo_name": "zoho/books-python-wrappers", "path": "test/EstimatesTest.py", "copies": "1", "size": "7474", "license": "mit", "hash": 2906424729921851400, "line_mean": 27.6360153257, "line_max": 154, "alpha_frac": 0.7567567568, "autogenerated": false, "ratio": 3.0833333333333335, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9300112632329378, "avg_score": 0.007995491560790885, "num_lines": 261 }
#$Id$# from books.model.Estimate import Estimate from books.model.EstimateList import EstimateList from books.model.Address import Address from books.model.Email import Email from books.model.ContactPerson import ContactPerson from books.model.LineItem import LineItem from books.model.PageContext import PageContext from books.model.Tax import Tax from books.model.CustomField import CustomField from books.model.Email import Email from books.model.EmailTemplate import EmailTemplate from books.model.ToContact import ToContact from books.model.FromEmail import FromEmail from books.model.Template import Template from books.model.Comment import Comment from books.model.CommentList import CommentList from books.model.TemplateList import TemplateList class EstimatesParser: """This class is used to parse the json for estimates.""" def get_list(self, response): """This method parses the given response and returns estimates list object. Args: response(dict): Response containing json object for estimates. Returns: instance: Estimates list object. """ resp = response['estimates'] estimate_list = EstimateList() for value in resp: estimates = Estimate() estimates.set_estimate_id(value['estimate_id']) estimates.set_customer_name(value['customer_name']) estimates.set_customer_id(value['customer_id']) estimates.set_status(value['status']) estimates.set_estimate_number(value['estimate_number']) estimates.set_reference_number(value['reference_number']) estimates.set_date(value['date']) estimates.set_currency_id(value['currency_id']) estimates.set_currency_code(value['currency_code']) estimates.set_total(value['total']) estimates.set_created_time(value['created_time']) estimates.set_accepted_date(value['accepted_date']) estimates.set_declined_date(value['declined_date']) estimates.set_expiry_date(value['expiry_date']) estimate_list.set_estimates(estimates) page_context_object = PageContext() page_context = response['page_context'] page_context_object.set_page(page_context['page']) page_context_object.set_per_page(page_context['per_page']) page_context_object.set_has_more_page(page_context['has_more_page']) page_context_object.set_report_name(page_context['report_name']) page_context_object.set_applied_filter(page_context['applied_filter']) page_context_object.set_sort_column(page_context['sort_column']) page_context_object.set_sort_order(page_context['sort_order']) estimate_list.set_page_context(page_context_object) return estimate_list def get_estimate(self, response): """This method parses the given response and returns Estimate object. Args: response(dict): Response containing json object for estimate. Returns: instance: Estimate object. """ estimate = Estimate() resp = response['estimate'] estimate.set_estimate_id(resp['estimate_id']) estimate.set_estimate_number(resp['estimate_number']) estimate.set_date(resp['date']) estimate.set_reference_number(resp['reference_number']) estimate.set_status(resp['status']) estimate.set_customer_id(resp['customer_id']) estimate.set_customer_name(resp['customer_name']) estimate.set_contact_persons(resp['contact_persons']) estimate.set_currency_id(resp['currency_id']) estimate.set_currency_code(resp['currency_code']) estimate.set_exchange_rate(resp['exchange_rate']) estimate.set_expiry_date(resp['expiry_date']) estimate.set_discount(resp['discount']) estimate.set_is_discount_before_tax(resp['is_discount_before_tax']) estimate.set_discount_type(resp['discount_type']) line_items = resp['line_items'] for value in line_items: line_item = LineItem() line_item.set_item_id(value['item_id']) line_item.set_line_item_id(value['line_item_id']) line_item.set_name(value['name']) line_item.set_description(value['description']) line_item.set_item_order(value['item_order']) line_item.set_bcy_rate(value['bcy_rate']) line_item.set_rate(value['rate']) line_item.set_quantity(value['quantity']) line_item.set_unit(value['unit']) line_item.set_discount(value['discount']) line_item.set_tax_id(value['tax_id']) line_item.set_tax_name(value['tax_name']) line_item.set_tax_type(value['tax_type']) line_item.set_tax_percentage(value['tax_percentage']) line_item.set_item_total(value['item_total']) estimate.set_line_items(line_item) estimate.set_shipping_charge(resp['shipping_charge']) estimate.set_adjustment(resp['adjustment']) estimate.set_adjustment_description(resp['adjustment_description']) estimate.set_sub_total(resp['sub_total']) estimate.set_total(resp['total']) estimate.set_tax_total(resp['tax_total']) estimate.set_price_precision(resp['price_precision']) taxes = resp['taxes'] for value in taxes: tax = Tax() tax.set_tax_name(value['tax_name']) tax.set_tax_amount(value['tax_amount']) estimate.set_taxes(tax) billing_address = resp['billing_address'] billing_address_object = Address() billing_address_object.set_address(billing_address['address']) billing_address_object.set_city(billing_address['city']) billing_address_object.set_state(billing_address['state']) billing_address_object.set_zip(billing_address['zip']) billing_address_object.set_country(billing_address['country']) billing_address_object.set_fax(billing_address['zip']) estimate.set_billing_address(billing_address_object) shipping_address = resp['shipping_address'] shipping_address_object = Address() shipping_address_object.set_address(shipping_address['address']) shipping_address_object.set_city(shipping_address['city']) shipping_address_object.set_state(shipping_address['state']) shipping_address_object.set_zip(shipping_address['zip']) shipping_address_object.set_country(shipping_address['country']) shipping_address_object.set_fax(shipping_address['zip']) estimate.set_shipping_address(shipping_address_object) estimate.set_notes(resp['notes']) estimate.set_terms(resp['terms']) custom_fields = resp['custom_fields'] for value in custom_fields: custom_field = CustomField() custom_field.set_index(value['index']) custom_field.set_show_on_pdf(value['show_on_pdf']) custom_field.set_value(value['value']) custom_field.set_label(value['label']) estimate.set_custom_fields(custom_field) estimate.set_template_id(resp['template_id']) estimate.set_template_name(resp['template_name']) estimate.set_created_time(resp['created_time']) estimate.set_last_modified_time(resp['last_modified_time']) estimate.set_salesperson_id(resp['salesperson_id']) estimate.set_salesperson_name(resp['salesperson_name']) return estimate def get_message(self, response): """This method parses the given response and returns success message. Args: response(dict): Response containing json object. Returns: str: Success message. """ return response['message'] def get_email_content(self, response): """This method parses the given response and returns email object. Args: response(dict): Response containing json object for email content. Returns: instance: Email object. """ email = Email() data = response['data'] email.set_body(data['body']) email.set_error_list(data['error_list']) email.set_subject(data['subject']) for value in data['emailtemplates']: email_templates = EmailTemplate() email_templates.set_selected(value['selected']) email_templates.set_name(value['name']) email_templates.set_email_template_id(value['email_template_id']) email.set_email_templates(email_templates) to_contacts = data['to_contacts'] for value in to_contacts: to_contact = ToContact() to_contact.set_first_name(value['first_name']) to_contact.set_selected(value['selected']) to_contact.set_phone(value['phone']) to_contact.set_email(value['email']) to_contact.set_contact_person_id(value['contact_person_id']) to_contact.set_last_name(value['last_name']) to_contact.set_salutation(value['salutation']) to_contact.set_mobile(value['mobile']) email.set_to_contacts(to_contact) email.set_file_name(data['file_name']) from_emails = data['from_emails'] for value in from_emails: from_email = FromEmail() from_email.set_user_name(value['user_name']) from_email.set_selected(value['selected']) from_email.set_email(value['email']) email.set_from_emails(from_email) email.set_customer_id(data['customer_id']) return email def get_billing_address(self, response): """This method parses the given response and returns billing address object. Args: response(dict): Response containing json object for billing address. Returns: instacne: Billing address object. """ address = response['billing_address'] address_object = Address() address_object.set_address(address['address']) address_object.set_city(address['city']) address_object.set_state(address['state']) address_object.set_zip(address['zip']) address_object.set_country(address['country']) address_object.set_fax(address['fax']) address_object.set_is_update_customer(address['is_update_customer']) return address_object def get_shipping_address(self, response): """This method parses the given response and returns shipping address object. Args: response(dict): Response containing json object for shipping address. Returns: instance: Shipping address object. """ address = response['shipping_address'] address_object = Address() address_object.set_address(address['address']) address_object.set_city(address['city']) address_object.set_state(address['state']) address_object.set_zip(address['zip']) address_object.set_country(address['country']) address_object.set_fax(address['fax']) address_object.set_is_update_customer(address['is_update_customer']) return address_object def estimate_template_list(self, response): """This method parses the given response and returns estimate template list object. Args: response(dict): Response containing json object for estimate template list. Returns: instance: Template list object. """ template_list = TemplateList() resp = response['templates'] for value in resp: template = Template() template.set_template_name(value['template_name']) template.set_template_id(value['template_id']) template.set_template_type(value['template_type']) template_list.set_templates(template) return template_list def get_comments(self, response): """This method parses the given response and returns comments list object. Args: response(dict): Response containing json object for comments list. Returns: instance: Comments list object. """ comments = response['comments'] comments_list = CommentList() for value in comments: comment = Comment() comment.set_comment_id(value['comment_id']) comment.set_estimate_id(value['estimate_id']) comment.set_description(value['description']) comment.set_commented_by_id(value['commented_by_id']) comment.set_commented_by(value['commented_by']) comment.set_comment_type(value['comment_type']) comment.set_date(value['date']) comment.set_date_description(value['date_description']) comment.set_time(value['time']) comment.set_operation_type(value['operation_type']) comment.set_transaction_id(value['transaction_id']) comment.set_transaction_type(value['transaction_type']) comments_list.set_comments(comment) return comments_list def get_comment(self, response): """This method parses the given response and returns comments object. Args: response(dict): Response containing json object for comments object. Returns: instance: Comments object. """ comment = response['comment'] comment_object = Comment() comment_object.set_comment_id(comment['comment_id']) comment_object.set_estimate_id(comment['estimate_id']) comment_object.set_description(comment['description']) comment_object.set_commented_by_id(comment['commented_by_id']) comment_object.set_commented_by(comment['commented_by']) comment_object.set_date(comment['date']) comment_object.set_date_description(comment['date_description']) comment_object.set_time(comment['time']) comment_object.set_comment_type(comment['comment_type']) return comment_object
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/EstimatesParser.py", "copies": "1", "size": "14344", "license": "mit", "hash": -4984356129707348000, "line_mean": 41.064516129, "line_max": 84, "alpha_frac": 0.6323898494, "autogenerated": false, "ratio": 4.202754175212423, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5335144024612423, "avg_score": null, "num_lines": null }
#$Id$# from books.model.Expense import Expense from books.model.ExpenseList import ExpenseList from books.model.Comment import Comment from books.model.PageContext import PageContext from books.model.CommentList import CommentList class ExpensesParser: """This class is used to parse the json for Expenses.""" def get_list(self, resp): """This method parses the given response and returns Expense list object. Args: resp(dict): Response containing json object for Expenses list. Returns: instance: Expenses list object. """ expenses = resp['expenses'] expense_list = ExpenseList() for value in expenses: expense = Expense() expense.set_expense_id(value['expense_id']) expense.set_date(value['date']) expense.set_account_name(value['account_name']) expense.set_paid_through_account_name(value[\ 'paid_through_account_name']) expense.set_description(value['description']) expense.set_currency_id(value['currency_id']) expense.set_currency_code(value['currency_code']) expense.set_bcy_total(value['bcy_total']) expense.set_total(value['total']) expense.set_is_billable(value['is_billable']) expense.set_reference_number(value['reference_number']) expense.set_customer_id(value['customer_id']) expense.set_customer_name(value['customer_name']) expense.set_vendor_id(value['vendor_id']) expense.set_vendor_name(value['vendor_name']) expense.set_status(value['status']) expense.set_created_time(value['created_time']) expense.set_expense_receipt_name(value['expense_receipt_name']) expense_list.set_expenses(expense) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) expense_list.set_page_context(page_context) return expense_list def get_expense(self, resp): """This method parses the given response and returns expense object. Args: resp(dict): Response containing json object for expense. Returns: instance: Expense object. """ expense = resp['expense'] expense_obj = Expense() expense_obj.set_expense_id(expense['expense_id']) expense_obj.set_expense_item_id(expense['expense_item_id']) expense_obj.set_account_id(expense['account_id']) expense_obj.set_account_name(expense['account_name']) expense_obj.set_paid_through_account_id(expense[\ 'paid_through_account_id']) expense_obj.set_paid_through_account_name(expense[\ 'paid_through_account_name']) expense_obj.set_vendor_id(expense['vendor_id']) expense_obj.set_vendor_name(expense['vendor_name']) expense_obj.set_date(expense['date']) expense_obj.set_tax_id(expense['tax_id']) expense_obj.set_tax_name(expense['tax_name']) expense_obj.set_tax_percentage(expense['tax_percentage']) expense_obj.set_currency_id(expense['currency_id']) expense_obj.set_currency_code(expense['currency_code']) expense_obj.set_exchange_rate(expense['exchange_rate']) expense_obj.set_tax_amount(expense['tax_amount']) expense_obj.set_sub_total(expense['sub_total']) expense_obj.set_total(expense['total']) expense_obj.set_bcy_total(expense['bcy_total']) expense_obj.set_amount(expense['amount']) expense_obj.set_is_inclusive_tax(expense['is_inclusive_tax']) expense_obj.set_reference_number(expense['reference_number']) expense_obj.set_description(expense['description']) expense_obj.set_is_billable(expense['is_billable']) expense_obj.set_customer_id(expense['customer_id']) expense_obj.set_customer_name(expense['customer_name']) expense_obj.set_expense_receipt_name(expense['expense_receipt_name']) expense_obj.set_created_time(expense['created_time']) expense_obj.set_last_modified_time(expense['last_modified_time']) expense_obj.set_status(expense['status']) expense_obj.set_invoice_id(expense['invoice_id']) expense_obj.set_invoice_number(expense['invoice_number']) expense_obj.set_project_id(expense['project_id']) expense_obj.set_project_name(expense['project_name']) return expense_obj def get_message(self, resp): """This method parses the given json string and returns string message. Args: resp(dict): Response containing json object for success message. Returns: str: Success message. """ return resp['message'] def get_comments(self, resp): """This method parses the given json string and returns comments list. Args: resp(dict): Response containing json object for comments. Returns: instance: Comments list object. """ comments = CommentList() for value in resp['comments']: comment = Comment() comment.set_comment_id(value['comment_id']) comment.set_expense_id(value['expense_id']) comment.set_description(value['description']) comment.set_commented_by_id(value['commented_by_id']) comment.set_commented_by(value['commented_by']) comment.set_date(value['date']) comment.set_date_description(value['date_description']) comment.set_time(value['time']) comment.set_operation_type(value['operation_type']) comment.set_transaction_id(value['transaction_id']) comment.set_transaction_type(value['transaction_type']) comments.set_comments(comment) return comments
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/ExpensesParser.py", "copies": "1", "size": "6400", "license": "mit", "hash": -2943403618658164000, "line_mean": 42.537414966, "line_max": 79, "alpha_frac": 0.6334375, "autogenerated": false, "ratio": 3.9603960396039604, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.509383353960396, "avg_score": null, "num_lines": null }
#$Id$# from books.model.Expense import Expense from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") expenses_api = zoho_books.get_expenses_api() expense_id = expenses_api.get_expenses().get_expenses()[0].get_expense_id() accounts_api = zoho_books.get_bank_accounts_api() account_id = accounts_api.get_bank_accounts().get_bank_accounts()[0].get_account_id() param = {'filter_by': 'AccountType.Expense'} chart_of_accounts_api = zoho_books.get_chart_of_accounts_api() expense_account_id = chart_of_accounts_api.get_chart_of_accounts(param).get_chartofaccounts()[1].get_account_id() settings_api = zoho_books.get_settings_api() currency_id = settings_api.get_currencies().get_currencies()[0].get_currency_id() contact_api = zoho_books.get_contacts_api() customer_id = contact_api.get_contacts().get_contacts()[0].get_contact_id() vendor_api = zoho_books.get_vendor_payments_api() vendor_id = vendor_api.get_vendor_payments().get_vendor_payments()[0].get_vendor_id() # List Expenses parameters={'filter_by':'Status.Unbilled'} print expenses_api.get_expenses() print expenses_api.get_expenses(parameters) # Get an expense print expenses_api.get(expense_id) # Create an expense expenses=Expense() expenses.set_account_id(expense_account_id) expenses.set_paid_through_account_id(account_id) expenses.set_date("2012-12-30") expenses.set_amount(100.0) expenses.set_tax_id("71127000000077019") expenses.set_is_inclusive_tax(True) expenses.set_is_billable(True) expenses.set_customer_id(customer_id) expenses.set_vendor_id(vendor_id) expenses.set_currency_id(currency_id) #expenses.set_exchange_rate() #expenses.set_project_id() print expenses_api.create(expenses) receipt="/{file_directory}/download.jpg" print expenses_api.create(expenses,receipt) # Update an expense expenses=Expense() expenses.set_account_id(expense_account_id) expenses.set_paid_through_account_id(account_id) expenses.set_date("2012-12-30") expenses.set_amount(100.0) expenses.set_tax_id("") expenses.set_is_inclusive_tax(True) expenses.set_is_billable(True) expenses.set_customer_id(customer_id) expenses.set_vendor_id(vendor_id) expenses.set_currency_id(currency_id) #expenses.set_exchange_rate() #expenses.set_project_id() print expenses_api.update(expense_id,expenses) receipt="/{file_directory}/download.jpg" print expenses_api.update(expense_id,expenses,receipt) # Delete an expense print expenses_api.delete(expense_id) ''' # List expense comments and history print expenses_api.list_comments_history(expense_id) ''' # Receipt #get an expense receipt print expenses_api.get_receipt(expense_id) print expenses_api.get_receipt(expense_id,True) # Get an expense receipt receipt="/{file_directory}/download.jpg" print expenses_api.add_receipt(expense_id,receipt) # Delete a receipt print expenses_api.delete_receipt(expense_id)
{ "repo_name": "zoho/books-python-wrappers", "path": "test/ExpensesTest.py", "copies": "1", "size": "2882", "license": "mit", "hash": -2973606415004084000, "line_mean": 26.1886792453, "line_max": 113, "alpha_frac": 0.7647467037, "autogenerated": false, "ratio": 2.7764932562620426, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.8955721558634413, "avg_score": 0.017103680265526007, "num_lines": 106 }
#$Id$# from books.model.Journal import Journal from books.model.JournalList import JournalList from books.model.PageContext import PageContext from books.model.LineItem import LineItem class JournalsParser: """This class is used to parse the given json for Jornals.""" def get_list(self, resp): """This method parses the given response for journals list. Args: journals(dict): Response containing json object for journals list. Returns: instance: Journals list object. """ journals_list = JournalList() for value in resp['journals']: journal = Journal() journal.set_journal_id(value['journal_id']) journal.set_journal_date(value['journal_date']) journal.set_entry_number(value['entry_number']) journal.set_reference_number(value['reference_number']) journal.set_notes(value['notes']) journal.set_total(value['total']) journals_list.set_journals(journal) page_context = resp['page_context'] page_context_obj = PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) if 'from_date' in page_context: page_context_obj.set_from_date(page_context['from_date']) if 'to_date' in page_context: page_context_obj.set_to_date(page_context['to_date']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) journals_list.set_page_context(page_context_obj) return journals_list def get_journal(self, resp): """This method parses the given response and returns journals object. Args: resp(dict): Response containing json object for journal. Returns: instance: Journal object. """ journal = resp['journal'] journal_obj = Journal() journal_obj.set_journal_id(journal['journal_id']) journal_obj.set_entry_number(journal['entry_number']) journal_obj.set_reference_number(journal['reference_number']) journal_obj.set_notes(journal['notes']) journal_obj.set_currency_id(journal['currency_id']) journal_obj.set_currency_symbol(journal['currency_symbol']) journal_obj.set_journal_date(journal['journal_date']) for value in journal['line_items']: line_item = LineItem() line_item.set_line_id(value['line_id']) line_item.set_account_id(value['account_id']) line_item.set_account_name(value['account_name']) line_item.set_description(value['description']) line_item.set_debit_or_credit(value['debit_or_credit']) line_item.set_tax_id(value['tax_id']) line_item.set_tax_name(value['tax_name']) line_item.set_tax_type(value['tax_type']) line_item.set_tax_percentage(value['tax_percentage']) line_item.set_amount(value['amount']) journal_obj.set_line_items(line_item) journal_obj.set_line_item_total(journal['line_item_total']) journal_obj.set_total(journal['total']) journal_obj.set_price_precision(journal['price_precision']) journal_obj.set_created_time(journal['created_time']) journal_obj.set_last_modified_time(journal['last_modified_time']) for value in journal['taxes']: tax = Tax() tax.set_tax_name(value['tax_name']) tax.set_tax_amount(value['tax_amount']) journal_obj.set_taxes(tax) return journal_obj def get_message(self, resp): """This method parses the given response and returns string message. Args: resp(dict): Response containing json object for message. Returns: str: Success message. """ return resp['message']
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/JournalsParser.py", "copies": "1", "size": "4222", "license": "mit", "hash": -3397812201225178000, "line_mean": 39.9902912621, "line_max": 78, "alpha_frac": 0.6205589768, "autogenerated": false, "ratio": 3.8912442396313365, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9980781087494612, "avg_score": 0.006204425787344946, "num_lines": 103 }
#$Id$ from books.model.PageContext import PageContext from books.model.Instrumentation import Instrumentation class TransactionList: """This class is used to create object for Transaction list.""" def __init__(self): """Initialize parameters for Transaction list object.""" self.transactions = [] self.page_context = PageContext() self.Instrumentation = Instrumentation() def set_transactions(self, transaction): """Set transactions. Args: transaction(instance): Transaction object. """ self.transactions.append(transaction) def get_transactions(self): """Get transactions. Returns: list of instance: List of transactions object. """ return self.transactions def set_page_context(self, page_context): """Set page context. Args: page_context(instance): Page context """ self.page_context = page_context def get_page_context(self): """Get page context. Returns: instance: Page context object. """ return self.page_context def set_instrumentation(self, instrumentation): """Set instrumentation. Args: instrumentation(instance): Instrumentation object. """ self.instrumentation = instrumentation def get_instrumentation(self): """Get instrumentation. Returns: instance: Instrumentation object. """ return self.instrumentation
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/TransactionList.py", "copies": "1", "size": "1583", "license": "mit", "hash": 6738915959775530000, "line_mean": 22.2794117647, "line_max": 67, "alpha_frac": 0.6032849021, "autogenerated": false, "ratio": 5.025396825396825, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.021530180699730873, "num_lines": 68 }
#$Id$ from books.model.PageContext import PageContext class Statement: """This class is used to create object for statement.""" def __init__(self): """Initialize parameters for Statement object.""" self.statement_id = '' self.from_date = '' self.to_date = '' self.source = '' self.transactions = [] self.page_context = PageContext() def set_statement_id(self, statement_id): """Set statement id. Args: statement_id(str): Statement id. """ self.statement_id = statement_id def get_statement_id(self): """Get statement id. Returns: str: Statement id. """ return self.statement_id def set_from_date(self, from_date): """Set from date. Args: from_date(str): From date. """ self.from_date = from_date def get_from_date(self): """Get from date. Returns: str: From date. """ return self.from_date def set_source(self, source): """Set source. Args: source(str): Source. """ self.source = source def get_source(self): """Get source. Returns: str: Source. """ return self.source def set_transactions(self, transactions): """Set transactions. Args: transactions(instance): Transactions object. """ self.transactions.append(transactions) def get_transactions(self): """Get transactions. Returns: list of instance: List of transactions object. """ return self.transaction def set_page_context(self, page_context): """Set page context. Args: page_context(instance): Page context object. """ self.page_context = page_context def get_page_context(self): """Get page context. Returns: instance: Page context object. """ return self.page_context def set_to_date(self, to_date): """Set to date. Args: to_date(str): To date. """ self.to_date = to_date def get_to_date(self): """Get to date. Returns: str: To date. """ return self.to_date
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Statement.py", "copies": "1", "size": "2414", "license": "mit", "hash": -2711008113147533300, "line_mean": 18.6260162602, "line_max": 60, "alpha_frac": 0.5111847556, "autogenerated": false, "ratio": 4.397085610200365, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5408270365800365, "avg_score": null, "num_lines": null }
#$Id$ from books.model.PlaceHolder import PlaceHolder class Autoreminder: """This class is used to create object for auto reminders.""" def __init__(self): """Initialize parameters for auto reminders object.""" self.payment_reminder_id = '' self.is_enabled = None self.notification_type = '' self.address_type = '' self.number_of_days = 0 self.subject = '' self.body = '' self.autoreminder_id = '' self.order = 0 self.name = '' self.cc_addresses = '' self.placeholder = PlaceHolder() def set_cc_addresses(self, cc_addresses): """Set cc addresses. Args: cc_addresses(str): Cc addresses. """ self.cc_addresses = cc_addresses def get_cc_addresses(self): """Get cc addresses. Returns: str: Cc addresses. """ return self.cc_addresses def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_payment_reminder_id(self, payment_reminder_id): """Set payment reminder id. Args: payment_reminder_id(str): Payment reminder id. """ self.payment_reminder_id = payment_reminder_id def get_payment_reminder_id(self): """Get payment reminder id. Returns: str: Payment reminder id. """ return self.payment_reminder_id def set_is_enabled(self, is_enabled): """Set whether it is enabled or not. Args: is_enabled(bool): True to enable else False. """ self.is_enabled = is_enabled def get_is_enabled(self): """Get is enabled. Returns: bool: True if enabled else false. """ return self.is_enabled def set_notification_type(self, notification_type): """Set notification type. Args: notification_type(str): Notification type. """ self.notification_type = notification_type def get_notification_type(self): """Get notification type. Returns: str: Notification type. """ return self.notification_type def set_address_type(self, address_type): """Set address type. Args: address_type(str): Address type. """ self.address_type = address_type def get_address_type(self): """Get address type. Returns: str: Address type. """ return self.address_type def set_number_of_days(self, number_of_days): """Set number of days. Args: number_of_days(int): Number of days. """ self.number_of_days = number_of_days def get_number_of_days(self): """Get number of days. Returns: int: Number of days. """ return self.number_of_days def set_subject(self, subject): """Set subject. Args: subject(str): Subject. """ self.subject = subject def get_subject(self): """Get subject. Returns: str: Subject. """ return self.subject def set_body(self, body): """Set body. Args: body(str): Body. """ self.body = body def get_body(self): """Get body. Returns: str: Body. """ return self.body def set_autoreminder_id(self, autoreminder_id): """Set autoreminder id. Args: autoreminder_id(str): Auto reminder id. """ self.autoreminder_id = autoreminder_id def get_autoreminder_id(self): """Get autoreminder id. Returns: str: Auto reminder id. """ return self.autoreminder_id def set_order(self, order): """Set order. Args: order(int): Order. """ self.order = order def get_order(self): """Get order. Returns: int: Order. """ return self.order def set_placeholders(self, placeholders): """Set place holders. Args: place_holders: Palce holders object. """ self.placeholders = placeholders def get_placeholders(self): """Get place holders. Returns: instance: Place holders. """ return self.placeholders def to_json(self): """This method is used to convert auto reminder object to json object. Returns: dict: Dictionary cocntaining json object for autoreminder. """ data = {} if self.is_enabled != '': data['is_enabled'] = self.is_enabled if self.notification_type != '': data['type'] = self.notification_type if self.address_type != '': data['address_type'] = self.address_type if self.subject != '': data['subject'] = self.subject if self.body != '': data['body'] = self.body return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Autoreminder.py", "copies": "1", "size": "5344", "license": "mit", "hash": 7491357850733476000, "line_mean": 19.875, "line_max": 78, "alpha_frac": 0.5160928144, "autogenerated": false, "ratio": 4.323624595469256, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5339717409869256, "avg_score": null, "num_lines": null }
#$Id$ from books.model.PlaceHolder import PlaceHolder class ManualReminder: """This class is used to create object for manual reminders.""" def __init__(self): """Initilaize parameters for manual reminders.""" self.manualreminder_id = '' self.type = '' self.subject = '' self.body = '' self.cc_me = None self.placeholder = PlaceHolder() def set_manualreminder_id(self, manualreminder_id): """Set manual reminder id. Args: manualreminder_id(str): Manual reminder id. """ self.manualreminder_id = manualreminder_id def get_manualreminder_id(self): """Get manual reminder id. Returns: str: Manual reminder id. """ return self.manualreminder_id def set_type(self, type): """Set type. Args: type(str): Type. """ self.type = type def get_type(self): """Get type. Returns: str: Type. """ return self.type def set_subject(self, subject): """Set subject. Args: subject(str): Subject. """ self.subject = subject def get_subject(self): """Get subject. Returns: str: Subject. """ return self.subject def set_body(self, body): """Set body. Args: body(str): Body. """ self.body = body def get_body(self): """Get body. Returns: str: Body. """ return self.body def set_cc_me(self, cc_me): """Set cc me. Args: cc_me(bool): True to cc me else false. """ self.cc_me = cc_me def get_cc_me(self): """Get cc me. Returns: bool: True to cc me else false. """ return self.cc_me def set_placeholders(self, placeholders): """Set place holders. Args: place_holders: Palce holders object. """ self.placeholders = placeholders def get_placeholders(self): """Get place holders. Returns: instance: Place holders. """ return self.placeholders def to_json(self): """"This method is used to convert manual reminder object to json format. Returns: dict: Dictionary containing json object for manual reminders. """ data = {} if self.subject != '': data['subject'] = self.subject if self.body != '': data['body'] = self.body if self.cc_me is not None: data['cc_me'] = self.cc_me return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/ManualReminder.py", "copies": "1", "size": "2755", "license": "mit", "hash": 355805212088449540, "line_mean": 18.8201438849, "line_max": 81, "alpha_frac": 0.5016333938, "autogenerated": false, "ratio": 4.2384615384615385, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0061101894537585015, "num_lines": 139 }
#$Id$ from books.model.Preference import Preference from books.model.CustomField import CustomField from books.model.PlaceholderAddressFormat import PlaceholderAddressFormat class PreferenceList: """This class is used to create object for Preferences list.""" def __init__(self): """Initialize parameters for preferences list.""" self.preferences = Preference() self.custom_fields = CustomField() self.placeholders_address_format = PlaceholderAddressFormat() def set_preferences(self, preference): """Set preferences. Args: preference(instance): Preference object. """ self.preferences = preference def get_preferences(self): """Get preferneces. Retruns: instance: Preferences object. """ return self.preferences def set_custom_fields(self, custom_fields): """Set custom fields. Args: custom_fields(instance): Custom fields. """ self.custom_fields = custom_fields def set_placeholders_address_format(self, placeholders_address_format): """Set placeholders address format. Args: placeholders_address_format(instance): Place holders address format. """ self.placeholdedrs_address_format = placeholders_address_format def get_placeholders_address_format(self): """Get placeholders address format. Returns: instance: Placeholders address format. """ return self.placeholders_address_format
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/PreferenceList.py", "copies": "1", "size": "1585", "license": "mit", "hash": -4094471790457171000, "line_mean": 25.8644067797, "line_max": 80, "alpha_frac": 0.6460567823, "autogenerated": false, "ratio": 4.876923076923077, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6022979859223078, "avg_score": null, "num_lines": null }
#$Id$# from books.model.Preference import Preference from books.model.Organization import Organization from books.model.Address import Address from books.model.User import User from books.model.Item import Item from books.model.InvoiceSetting import InvoiceSetting from books.model.NotesAndTerms import NotesAndTerms from books.model.EstimateSetting import EstimateSetting from books.model.CreditnoteSetting import CreditnoteSetting from books.model.Currency import Currency from books.model.ExchangeRate import ExchangeRate from books.model.Tax import Tax from books.model.OpeningBalance import OpeningBalance from books.model.Account import Account from books.model.Autoreminder import Autoreminder from books.model.ManualReminder import ManualReminder from books.model.TaxGroup import TaxGroup from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") settings_api = zoho_books.get_settings_api() organizations_api = zoho_books.get_organizations_api() users_api = zoho_books.get_users_api() items_api = zoho_books.get_items_api() currency_id = settings_api.get_currencies().get_currencies()[0].get_currency_id() #List preferences print settings_api.list_preferences() #Update preference preference = Preference() preference.set_convert_to_invoice(False) preference.set_notify_me_on_online_payment(True) preference.set_send_payment_receipt_acknowledgement("") preference.set_auto_notify_recurring_invoice("") preference.set_snail_mail_include_payment_stub("") preference.set_is_show_powered_by(True) preference.set_attach_expense_receipt_to_invoice("") preference.set_allow_auto_categorize("") print settings_api.update_preferences(preference) # Create a unit print settings_api.create_unit("m") #Delete unit unit_id = "71127000000179031" print settings_api.delete_unit(unit_id) #Organization organization_id = organizations_api.get_organizations()[0].get_organization_id() # List organizations. print organizations_api.get_organizations() #Get organization print organizations_api.get(organization_id) #Create organization organization = Organization() organization.set_name("Jony and co") address = Address() address.set_street_address1("2/65") address.set_street_address2("vignesh plaza") address.set_city("MDU") address.set_state("TN") address.set_country("India") address.set_zip("322") organization.set_address(address) organization.set_industry_type("") organization.set_industry_size("") organization.set_fiscal_year_start_month("january") organization.set_currency_code("USD") organization.set_time_zone("Asia/Calcutta") organization.set_date_format("dd MMM yyyy") organization.set_field_separator("") organization.set_language_code("en") organization.set_tax_basis("accrual") organization.set_tax_type("tax") organization.set_org_address("") organization.set_remit_to_address("") print organizations_api.create(organization) #Update organization organization = Organization() organization.set_name("Jony and co") address = Address() address.set_street_address1("2/65") address.set_street_address2("vignesh plaza") address.set_city("MDU") address.set_state("TN") address.set_country("India") address.set_zip("322") organization.set_address(address) organization.set_industry_type("") organization.set_industry_size("") organization.set_fiscal_year_start_month("january") organization.set_currency_code("INR") organization.set_time_zone("Asia/Calcutta") organization.set_date_format("dd MMM yyyy") organization.set_field_separator("") organization.set_language_code("en") organization.set_tax_basis("accrual") organization.set_tax_type("tax") organization.set_org_address("") organization.set_remit_to_address("") print organizations_api.update(organization_id, organization) # User user_id = users_api.get_users().get_users()[0].get_user_id() #List user print users_api.get_users() param = {'filter_by': 'Status.All'} print users_api.get_users(param) # Get user print users_api.get(user_id) # current user print users_api.current_user() #Create user user = User() user.set_name("karanya") user.set_email("lek1000@d.com") user.set_user_role("staff") print users_api.create(user) #update user user = User() user.set_name("vakaa") user.set_email("lekha10@d.com") user.set_user_role("staff") print users_api.update(user_id, user) #delete user print users_api.delete(user_id) #Invite user print users_api.invite_user(user_id) #Mark user as active print users_api.mark_user_as_active(user_id) #Mark user as inactive print users_api.mark_user_as_inactive(user_id) # Item item_id = items_api.list_items().get_items()[0].get_item_id() # List items. print items_api.list_items() # Get an item print items_api.get(item_id) # Create item item = Item() item.set_name("Item 2") item.set_description("Item") item.set_rate(10.0) item.set_account_id("") item.set_tax_id("") print items_api.create(item) #Update item item = Item() item.set_name("item 1") item.set_description("Item") item.set_rate(100.0) item.set_account_id("") item.set_tax_id("") print items_api.update(item_id, item) #Delete item print items_api.delete_item(item_id) #Mark item as active print items_api.mark_item_as_active(item_id) #Mark item as inactive print items_api.mark_item_as_inactive(item_id) #Invoice Settings #Get invoice settings print settings_api.get_invoice_settings() #update invoice settings invoice_settings = InvoiceSetting() invoice_settings.set_auto_generate(True) invoice_settings.set_prefix_string("INV") invoice_settings.set_start_at(1) invoice_settings.set_next_number("43") invoice_settings.set_quantity_precision(2) #invoice_settings.set_discount_enabled(False) invoice_settings.set_reference_text("") #invoice_settings.set_default_template_id("") invoice_settings.set_notes("Hai") invoice_settings.set_terms("") invoice_settings.set_is_shipping_charge_required(True) invoice_settings.set_is_adjustment_required(True) invoice_settings.set_invoice_item_type("") invoice_settings.set_discount_type("item_level") invoice_settings.set_warn_convert_to_open(True) invoice_settings.set_warn_create_creditnotes(True) invoice_settings.set_is_open_invoice_editable(True) invoice_settings.set_is_sales_person_required(True) print settings_api.update_invoice_settings(invoice_settings) #Get invoice notes and terms print settings_api.get_invoice_notes_and_terms() #Update invoice notes and terms notes_and_terms = NotesAndTerms() notes_and_terms.set_notes("Thanks") notes_and_terms.set_terms("") print settings_api.update_invoice_notes_and_terms(notes_and_terms) """ #Estimates #Get estimates settings. """ print settings_api.get_estimate_settings() #update estimate settings estimate_settings = EstimateSetting() estimate_settings.set_auto_generate(True) estimate_settings.set_prefix_string("EST-") estimate_settings.set_start_at(2) estimate_settings.set_next_number("041") estimate_settings.set_quantity_precision(2) estimate_settings.set_discount_type("item_level") estimate_settings.set_reference_text("") estimate_settings.set_notes("Hai") estimate_settings.set_terms("") estimate_settings.set_terms_to_invoice(True) estimate_settings.set_notes_to_invoice(True) estimate_settings.set_warn_estimate_to_invoice(True) estimate_settings.set_is_sales_person_required(True) print settings_api.update_estimate_settings(estimate_settings) #Get estimates notes and terms. print settings_api.get_estimates_notes_and_terms() #update estimate notes and terms notes_and_terms = NotesAndTerms() notes_and_terms.set_notes("Thanks") notes_and_terms.set_terms("") print settings_api.update_estimates_notes_and_terms(notes_and_terms) """ #Creditnotes #List credit note """ print settings_api.list_creditnote_settings() #Update creditnotes settings creditnote_settings = CreditnoteSetting() creditnote_settings.set_auto_generate(True) creditnote_settings.set_prefix_string("CN-") creditnote_settings.set_reference_text("") creditnote_settings.set_next_number("0027") creditnote_settings.set_notes("Thank you") creditnote_settings.set_terms("Conditions Apply") print settings_api.update_creditnote_settings(creditnote_settings) #Get creditnote notes and terms print settings_api.get_creditnote_notes_and_terms() #update creditnote notes and terms notes_and_terms = NotesAndTerms() notes_and_terms.set_notes("Thanks") notes_and_terms.set_terms("") print settings_api.update_creditnote_notes_and_terms(notes_and_terms) """ #Currency and exchange rate #List currencies """ print settings_api.get_currencies() #Get a currency print settings_api.get_currency(currency_id) #Create a currency currency = Currency() currency.set_currency_code("NPR") currency.set_currency_symbol("") currency.set_price_precision(1) currency.set_currency_format("1,234,567.89") print settings_api.create_currency(currency) #Update currency currency = Currency() currency.set_currency_code("NPR") currency.set_currency_symbol("") currency.set_price_precision(1) currency.set_currency_format("1,234,567.89") print settings_api.update_currency(currency_id , currency) #Delete currency print settings_api.delete_currency(currency_id) """ #List exchange rates exchange_rate_id = settings_api.list_exchange_rates(currency_id).get_exchange_rates()[0].get_exchange_rate_id() """ print settings_api.list_exchange_rates(currency_id) #Get exchange rate print settings_api.get_exchange_rate(currency_id, exchange_rate_id) #Create an exchange rate exchange_rate = ExchangeRate() exchange_rate.set_currency_id(currency_id) exchange_rate.set_currency_code("NPR") exchange_rate.set_effective_date("2014-05-08") exchange_rate.set_rate(25.0) print settings_api.create_exchange_rate(exchange_rate) #Update an exchange rate exchange_rate = ExchangeRate() exchange_rate.set_exchange_rate_id(exchange_rate_id) exchange_rate.set_currency_id(currency_id) exchange_rate.set_currency_code("EUR") exchange_rate.set_effective_date("2014-05-08") exchange_rate.set_rate(25.0) print settings_api.update_exchange_rate(exchange_rate) #Delete an exchange rate print settings_api.delete_exchange_rate(currency_id, exchange_rate_id) """ #Tax and Tax group tax_id = settings_api.get_taxes().get_taxes()[0].get_tax_id() tax_group_id = "71127000000184003" #List taxes """ print settings_api.get_taxes() #Get a tax print settings_api.get_tax(tax_id) #Create tax tax = Tax() tax.set_tax_name("tax-1") tax.set_tax_percentage(10.5) tax.set_tax_type("tax") print settings_api.create_tax(tax) #update tax tax = Tax() tax.set_tax_name("Shipping_tax1") tax.set_tax_percentage(10.5) tax.set_tax_type("tax") print settings_api.update_tax(tax_id, tax) #Delete tax print settings_api.delete_tax(tax_id) #Get tax group print settings_api.get_tax_group(tax_group_id) #Create tax group tax_group = TaxGroup() tax_group.set_tax_group_name("group_taxes") taxes = "71127000000183009,71127000000191007" tax_group.set_taxes(taxes) print settings_api.create_tax_group(tax_group) #update tax group tax_group = TaxGroup() tax_group.set_tax_group_name("group_taxes") taxes = "71127000000185001,71127000000183007" tax_group.set_taxes(taxes) tax_group.set_tax_group_id(tax_group_id) print settings_api.update_tax_group(tax_group) #Delete tax group tax_group_id = "711270" print settings_api.delete_tax_group(tax_group_id) """ #Opening balance #Get opening balance """ print settings_api.get_opening_balance() #Create opening balance account_id="71127000000170302" opening_balance = OpeningBalance() opening_balance.set_date('2014-05-09') accounts = Account() accounts.set_account_id(account_id) accounts.set_debit_or_credit("debit") accounts.set_exchange_rate(1.0) accounts.set_currency_id(currency_id) accounts.set_amount(200.0) opening_balance.set_accounts(accounts) print settings_api.create_opening_balance(opening_balance) #Update opening balance account_id="71127000000170302" opening_balance = OpeningBalance() opening_balance.set_opening_balance_id("71127000000186001") opening_balance.set_date('2014-05-09') accounts = Account() accounts.set_account_id(account_id) accounts.set_debit_or_credit("debit") accounts.set_exchange_rate(1.0) accounts.set_currency_id("71127000000000099") accounts.set_amount(2000.0) opening_balance.set_accounts(accounts) print settings_api.update_opening_balance(opening_balance) #Delete opening balance print settings_api.delete_opening_balance() """ #Auto payment reminder auto_payment_reminder_id = settings_api.list_auto_payment_reminder().get_auto_reminders()[0].get_autoreminder_id() #List auto payment reminder """ print settings_api.list_auto_payment_reminder() """ #Get an auto payment reminder print settings_api.get_auto_payment_reminder(auto_payment_reminder_id) """ #Update an auto reminder autoreminder = Autoreminder() autoreminder.set_is_enabled(True) autoreminder.set_notification_type('days_after_due_date') autoreminder.set_address_type('remind_me') autoreminder.set_number_of_days(3) autoreminder.set_subject('hai') autoreminder.set_body('Reminder') print settings_api.update_auto_reminder(reminder_id, autoreminder) """ #List manual reminders reminder_id = settings_api.list_manual_reminders().get_manual_reminders()[0].get_manualreminder_id() """ print settings_api.list_manual_reminders() """ #Get a manual reminder print settings_api.get_manual_reminder(reminder_id) """ #Update a manual reminder manual_reminder = ManualReminder() manual_reminder.set_subject("Hello") manual_reminder.set_body("Manual reminder") manual_reminder.set_cc_me(False) print settings_api.update_manual_reminder(reminder_id, manual_reminder) """
{ "repo_name": "zoho/books-python-wrappers", "path": "test/SettingsTest.py", "copies": "1", "size": "13524", "license": "mit", "hash": 3145394848137122000, "line_mean": 25.5176470588, "line_max": 114, "alpha_frac": 0.7777284827, "autogenerated": false, "ratio": 3.037053671682012, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.4314782154382012, "avg_score": null, "num_lines": null }
#$Id$# from books.model.PreferenceList import PreferenceList from books.model.Preference import Preference from books.model.CustomField import CustomField from books.model.PlaceholderAddressFormat import PlaceholderAddressFormat from books.model.Autoreminder import Autoreminder from books.model.AutoReminderList import AutoReminderList from books.model.Term import Term from books.model.AddressFormat import AddressFormat from books.model.Invoice import Invoice from books.model.Estimate import Estimate from books.model.Contact import Contact from books.model.Organization import Organization from books.model.Customer import Customer from books.model.Organization import Organization from books.model.Address import Address from books.model.UserList import UserList from books.model.User import User from books.model.EmailId import EmailId from books.model.PageContext import PageContext from books.model.Item import Item from books.model.ItemList import ItemList from books.model.InvoiceSetting import InvoiceSetting from books.model.NotesAndTerms import NotesAndTerms from books.model.EstimateSetting import EstimateSetting from books.model.CreditnoteSetting import CreditnoteSetting from books.model.CurrencyList import CurrencyList from books.model.Currency import Currency from books.model.ExchangeRate import ExchangeRate from books.model.ExchangeRateList import ExchangeRateList from books.model.TaxList import TaxList from books.model.Tax import Tax from books.model.TaxGroup import TaxGroup from books.model.OpeningBalance import OpeningBalance from books.model.Account import Account from books.model.PlaceHolder import PlaceHolder from books.model.ManualReminder import ManualReminder from books.model.ManualReminderList import ManualReminderList class SettingsParser: """This class is used to parse the json for Settings.""" def preference_list(self, resp): """This method parses the given response and returns preferneces object. Args: resp(dict): Response containing json obejct for preferences. Returns: instance: Prefenreces object. Raises: Books Exception: If status is not '200' or '201'. """ preferences = resp['preferences'] preferences_list = PreferenceList() preference_obj = Preference() preference_obj.set_convert_to_invoice(preferences[\ 'convert_to_invoice']) preference_obj.set_attach_pdf_for_email(preferences[\ 'attach_pdf_for_email']) preference_obj.set_estimate_approval_status(preferences[\ 'estimate_approval_status']) preference_obj.set_notify_me_on_online_payment(preferences[\ 'notify_me_on_online_payment']) preference_obj.set_send_payment_receipt_acknowledgement(preferences[\ 'send_payment_receipt_acknowledgement']) preference_obj.set_auto_notify_recurring_invoice(preferences[\ 'auto_notify_recurring_invoice']) preference_obj.set_snail_mail_include_payment_stub(preferences[\ 'snail_mail_include_payment_stub']) preference_obj.set_is_show_powered_by(preferences['is_show_powered_by']) preference_obj.set_attach_expense_receipt_to_invoice(preferences[\ 'attach_expense_receipt_to_invoice']) preference_obj.set_is_estimate_enabled(preferences[\ 'is_estimate_enabled']) preference_obj.set_is_project_enabled(preferences['is_project_enabled']) preference_obj.set_is_purchaseorder_enabled(preferences[\ 'is_purchaseorder_enabled']) preference_obj.set_is_salesorder_enabled(preferences[\ 'is_salesorder_enabled']) preference_obj.set_is_pricebooks_enabled(preferences[\ 'is_pricebooks_enabled']) preference_obj.set_attach_payment_receipt_with_acknowledgement(\ preferences['attach_payment_receipt_with_acknowledgement']) for value in preferences['auto_reminders']: auto_reminder = Autoreminder() auto_reminder.set_payment_reminder_id(value['payment_reminder_id']) auto_reminder.set_is_enabled(value['is_enabled']) auto_reminder.set_notification_type(value['notification_type']) auto_reminder.set_address_type(value['address_type']) auto_reminder.set_number_of_days(value['number_of_days']) auto_reminder.set_subject(value['subject']) auto_reminder.set_body(value['body']) preference_obj.set_auto_reminders(auto_reminder) terms = preferences['terms'] terms_obj = Term() terms_obj.set_invoice_terms(terms['invoice_terms']) terms_obj.set_estimate_terms(terms['estimate_terms']) terms_obj.set_creditnote_terms(terms['creditnote_terms']) preference_obj.set_terms(terms_obj) address_formats_obj = AddressFormat() address_formats = preferences['address_formats'] address_formats_obj.set_organization_address_format(address_formats[\ 'organization_address_format']) address_formats_obj.set_customer_address_format(address_formats[\ 'customer_address_format']) preference_obj.set_address_formats(address_formats_obj) preferences_list.set_preferences(preference_obj) custom_fields = resp['customfields'] custom_fields_obj = CustomField() for value in custom_fields['invoice']: invoice = Invoice() invoice.set_index(value['index']) invoice.set_show_in_all_pdf(value['show_in_all_pdf']) invoice.set_label(value['label']) custom_fields_obj.set_invoice(invoice) for value in custom_fields['contact']: contact = Contact() contact.set_index(value['index']) contact.set_show_in_all_pdf(vlaue['show_in_all_pdf']) contact.set_label(value['label']) custom_fields_obj.set_contact(contact) for value in custom_fields['estimate']: estimate = Estimate() estimate.set_index(value['index']) estimate.set_show_in_all_pdf(value['show_in_all_pdf']) estimate.set_label(value['label']) custom_fields_obj.set_estimate(estimate) preferences_list.set_custom_fields(custom_fields_obj) placeholders_address_format = resp['placeholders_address_format'] placeholders_address_format_obj = PlaceholderAddressFormat() for value in placeholders_address_format['organization']: organization = Organization() organization.set_value(value['value']) organization.set_name(value['name']) placeholders_address_format_obj.set_organization(organization) for value in placeholders_address_format['customer']: customer = Customer() customer.set_name(value['name']) customer.set_value(value['value']) placeholders_address_format_obj.set_customer(customer) preferences_list.set_placeholders_address_format(\ placeholders_address_format_obj) return preferences_list def get_message(self, resp): """This message parses the given response and returns message string. Args: resp(dict): Response containing json object for message. Returns: str: Success message. """ return resp['message'] def get_organizations(self, resp): """This message parses the given response and returns organizations list. Args: resp(dict): Response containing json object for organizations list. Returns: instance: Organizations list object. """ organizations_list = [] for value in resp['organizations']: organization = Organization() organization.set_organization_id(value['organization_id']) organization.set_name(value['name']) organization.set_contact_name(value['contact_name']) organization.set_email(value['email']) organization.set_is_default_org(value['is_default_org']) organization.set_version(value['version']) organization.set_plan_type(value['plan_type']) organization.set_tax_group_enabled(value['tax_group_enabled']) organization.set_plan_name(value['plan_name']) organization.set_plan_period(value['plan_period']) organization.set_language_code(value['language_code']) organization.set_fiscal_year_start_month(value[\ 'fiscal_year_start_month']) organization.set_account_created_date(value[\ 'account_created_date']) organization.set_account_created_date_formatted(value[\ 'account_created_date_formatted']) organization.set_time_zone(value['time_zone']) organization.set_is_org_active(value['is_org_active']) organization.set_currency_id(value['currency_id']) organization.set_currency_code(value['currency_code']) organization.set_currency_symbol(value['currency_symbol']) organization.set_currency_format(value['currency_format']) organization.set_price_precision(value['price_precision']) organizations_list.append(organization) return organizations_list def get_organization(self, resp): """This method parses the given response and returns organization object. Args: resp(dict): Response containing json object for organization. """ organization = resp['organization'] organization_obj = Organization() organization_obj.set_organization_id(organization['organization_id']) organization_obj.set_name(organization['name']) organization_obj.set_is_default_org(organization['is_default_org']) organization_obj.set_user_role(organization['user_role']) organization_obj.set_account_created_date(organization[\ 'account_created_date']) organization_obj.set_time_zone(organization['time_zone']) organization_obj.set_language_code(organization['language_code']) organization_obj.set_date_format(organization['date_format']) organization_obj.set_field_separator(organization['field_separator']) organization_obj.set_fiscal_year_start_month(organization[\ 'fiscal_year_start_month']) organization_obj.set_contact_name(organization['contact_name']) organization_obj.set_industry_type(organization['industry_type']) organization_obj.set_industry_size(organization['industry_size']) organization_obj.set_company_id_label(organization['company_id_label']) organization_obj.set_company_id_value(organization['company_id_value']) organization_obj.set_tax_id_label(organization['tax_id_label']) organization_obj.set_tax_id_value(organization['tax_id_value']) organization_obj.set_currency_id(organization['currency_id']) organization_obj.set_currency_code(organization['currency_code']) organization_obj.set_currency_symbol(organization['currency_symbol']) organization_obj.set_currency_format(organization['currency_format']) organization_obj.set_price_precision(organization['price_precision']) address = organization['address'] address_obj = Address() address_obj.set_street_address1(address['street_address1']) address_obj.set_street_address2(address['street_address2']) address_obj.set_city(address['city']) address_obj.set_state(address['state']) address_obj.set_country(address['country']) address_obj.set_zip(address['zip']) organization_obj.set_address(address_obj) organization_obj.set_org_address(organization['org_address']) organization_obj.set_remit_to_address(organization['remit_to_address']) organization_obj.set_phone(organization['phone']) organization_obj.set_fax(organization['fax']) organization_obj.set_website(organization['website']) organization_obj.set_email(organization['email']) organization_obj.set_tax_basis(organization['tax_basis']) for value in organization['custom_fields']: custom_field = CustomField() custom_field.set_value(value['value']) custom_field.set_index(value['index']) custom_field.set_label(value['label']) organization_obj.set_custom_fields(custom_field) organization_obj.set_is_org_active(organization['is_org_active']) organization_obj.set_is_new_customer_custom_fields(organization[\ 'is_new_customer_custom_fields']) organization_obj.set_is_portal_enabled(organization['is_portal_enabled']) organization_obj.set_portal_name(organization['portal_name']) return organization_obj def get_users(self, resp): """This method parses the given response and returns USers list object. Args: resp(dict): Response containing json object for users list. Returns: instance: Users list object. """ users_list = UserList() for value in resp['users']: user = User() user.set_user_id(value['user_id']) user.set_role_id(value['role_id']) user.set_name(value['name']) user.set_email(value['email']) user.set_user_role(value['user_role']) user.set_status(value['status']) user.set_is_current_user(value['is_current_user']) user.set_photo_url(value['photo_url']) users_list.set_users(user) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) users_list.set_page_context(page_context_obj) return users_list def get_user(self, resp): """This method parses the given response and returns user object. Args: resp(dict): Response containing json object for user. Returns: instance: User object. Raises: Books Exception: If status is not '200' or '201'. """ user = resp['user'] user_obj = User() user_obj.set_user_id(user['user_id']) user_obj.set_name(user['name']) for value in user['email_ids']: email_id = EmailId() email_id.set_is_selected(value['is_selected']) email_id.set_email(value['email']) user_obj.set_email_ids(email_id) user_obj.set_status(user['status']) user_obj.set_user_role(user['user_role']) user_obj.set_created_time(user['created_time']) user_obj.set_photo_url(user['photo_url']) return user_obj def get_items(self, resp): """This method parses the given response and returns items list object. Args: resp(dict): Response containing json object for items list. Returns: instance: Items list object. """ items_list = ItemList() for value in resp['items']: item = Item() item.set_item_id(value['item_id']) item.set_name(value['name']) item.set_status(value['status']) item.set_description(value['description']) item.set_rate(value['rate']) item.set_tax_id(value['tax_id']) item.set_tax_name(value['tax_name']) item.set_tax_percentage(value['tax_percentage']) items_list.set_items(item) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) items_list.set_page_context(page_context_obj) return items_list def get_item(self, resp): """This method parses the given response and returns item object. Args: resp(dict): Response containing json object for item. Returns: instance: Item object. """ item = resp['item'] item_obj = Item() item_obj.set_item_id(item['item_id']) item_obj.set_name(item['name']) item_obj.set_status(item['status']) item_obj.set_description(item['description']) item_obj.set_rate(item['rate']) item_obj.set_unit(item['unit']) item_obj.set_account_id(item['account_id']) item_obj.set_account_name(item['account_name']) item_obj.set_tax_id(item['tax_id']) item_obj.set_tax_name(item['tax_name']) item_obj.set_tax_percentage(item['tax_percentage']) item_obj.set_tax_type(item['tax_type']) return item_obj def get_invoice_settings(self, resp): """This method parses the given response and returns invoice settings object. Args: resp(dict): Response containing json object for invoice settings. Returns: instance: Invoice settings object. """ invoice_settings = resp['invoice_settings'] invoice_settings_obj = InvoiceSetting() invoice_settings_obj.set_auto_generate(invoice_settings[\ 'auto_generate']) invoice_settings_obj.set_prefix_string(invoice_settings[\ 'prefix_string']) invoice_settings_obj.set_start_at(invoice_settings['start_at']) invoice_settings_obj.set_next_number(invoice_settings['next_number']) invoice_settings_obj.set_quantity_precision(invoice_settings[\ 'quantity_precision']) invoice_settings_obj.set_discount_type(invoice_settings[\ 'discount_type']) invoice_settings_obj.set_is_discount_before_tax(invoice_settings[\ 'is_discount_before_tax']) invoice_settings_obj.set_reference_text(invoice_settings[\ 'reference_text']) invoice_settings_obj.set_notes(invoice_settings['notes']) invoice_settings_obj.set_terms(invoice_settings['terms']) invoice_settings_obj.set_is_shipping_charge_required(invoice_settings[\ 'is_shipping_charge_required']) invoice_settings_obj.set_is_adjustment_required(invoice_settings[\ 'is_adjustment_required']) invoice_settings_obj.set_is_open_invoice_editable(invoice_settings[\ 'is_open_invoice_editable']) invoice_settings_obj.set_warn_convert_to_open(invoice_settings[\ 'warn_convert_to_open']) invoice_settings_obj.set_warn_create_creditnotes(invoice_settings[\ 'warn_create_creditnotes']) invoice_settings_obj.set_attach_expense_receipt_to_invoice(\ invoice_settings['attach_expense_receipt_to_invoice']) invoice_settings_obj.set_invoice_item_type(invoice_settings[\ 'invoice_item_type']) invoice_settings_obj.set_is_sales_person_required(invoice_settings[\ 'is_sales_person_required']) return invoice_settings_obj def get_notes_and_terms(self, resp): """This method parses the given response and returns notes and terms object. Args: resp(dict): Dictionary containing json object for estimate settings. Returns: instance: Notes and terms object. """ notes_and_terms = resp['notes_and_terms'] notes_and_terms_obj = NotesAndTerms() notes_and_terms_obj.set_notes(notes_and_terms['notes']) notes_and_terms_obj.set_terms(notes_and_terms['terms']) return notes_and_terms_obj def get_estimate_settings(self, resp): """This method parses the given response and returns estimate settings object. Args: resp: Dictionary containing json object for estimate settings. Returns: instance: Estimate settings object. """ estimate_settings = resp['estimate_settings'] estimate_settings_obj = EstimateSetting() estimate_settings_obj.set_auto_generate(estimate_settings[\ 'auto_generate']) estimate_settings_obj.set_prefix_string(estimate_settings[\ 'prefix_string']) estimate_settings_obj.set_start_at(estimate_settings['start_at']) estimate_settings_obj.set_next_number(estimate_settings['next_number']) estimate_settings_obj.set_quantity_precision(estimate_settings[\ 'quantity_precision']) estimate_settings_obj.set_discount_type(estimate_settings[\ 'discount_type']) estimate_settings_obj.set_is_discount_before_tax(estimate_settings[\ 'is_discount_before_tax']) estimate_settings_obj.set_reference_text(estimate_settings[\ 'reference_text']) estimate_settings_obj.set_notes(estimate_settings['notes']) estimate_settings_obj.set_terms(estimate_settings['terms']) estimate_settings_obj.set_terms_to_invoice(estimate_settings[\ 'terms_to_invoice']) estimate_settings_obj.set_notes_to_invoice(estimate_settings[\ 'notes_to_invoice']) estimate_settings_obj.set_warn_estimate_to_invoice(estimate_settings[\ 'warn_estimate_to_invoice']) estimate_settings_obj.set_is_sales_person_required(estimate_settings[\ 'is_sales_person_required']) return estimate_settings_obj def get_creditnote_settings(self, resp): """This method parses the given response and returns creditnote settings. Args: resp(dict): Dictionary containing json object for creditnote settings. Returns: instance: Creditnotes settings object. """ creditnote_settings_obj = CreditnoteSetting() creditnote_settings = resp['creditnote_settings'] creditnote_settings_obj.set_auto_generate(creditnote_settings[\ 'auto_generate']) creditnote_settings_obj.set_prefix_string(creditnote_settings[\ 'prefix_string']) creditnote_settings_obj.set_reference_text(creditnote_settings[\ 'reference_text']) creditnote_settings_obj.set_next_number(creditnote_settings[\ 'next_number']) creditnote_settings_obj.set_notes(creditnote_settings['notes']) creditnote_settings_obj.set_terms(creditnote_settings['terms']) return creditnote_settings_obj def get_currencies(self, resp): """This method parses the given response and returns currency list object. Args: resp(dict): Response containing json object for list of currencies. Returns: instance: Currency list object. """ currency_list = CurrencyList() for value in resp['currencies']: currency = Currency() currency.set_currency_id(value['currency_id']) currency.set_currency_code(value['currency_code']) currency.set_currency_name(value['currency_name']) currency.set_currency_symbol(value['currency_symbol']) currency.set_price_precision(value['price_precision']) currency.set_currency_format(value['currency_format']) currency.set_is_base_currency(value['is_base_currency']) currency.set_exchange_rate(value['exchange_rate']) currency.set_effective_date(value['effective_date']) currency_list.set_currencies(currency) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) currency_list.set_page_context(page_context_obj) return currency_list def get_currency(self, resp): """This method parses the given response and returns currency object. Args: resp(dict): Response containing json object for currency. Returns: instance: Currency object. """ currency_obj = Currency() currency = resp['currency'] currency_obj.set_currency_id(currency['currency_id']) currency_obj.set_currency_code(currency['currency_code']) currency_obj.set_currency_name(currency['currency_name']) currency_obj.set_currency_symbol(currency['currency_symbol']) currency_obj.set_price_precision(currency['price_precision']) currency_obj.set_currency_format(currency['currency_format']) currency_obj.set_is_base_currency(currency['is_base_currency']) return currency_obj def get_exchange_rates(self, resp): """This method parses the given response and returns exchange rates list. Args: resp(dict): Response containing json object for exchange rate. Returns: list of instance: List of exchange rates object. """ exchange_rates = ExchangeRateList() for value in resp['exchange_rates']: exchange_rate = ExchangeRate() exchange_rate.set_exchange_rate_id(value['exchange_rate_id']) exchange_rate.set_currency_id(value['currency_id']) exchange_rate.set_currency_code(value['currency_code']) exchange_rate.set_effective_date(value['effective_date']) exchange_rate.set_rate(value['rate']) exchange_rates.set_exchange_rates(exchange_rate) return exchange_rates def get_exchange_rate(self, resp): """This method parses the given response and returns exchange rate object. Args: resp(dict): Response containing json object for exchange rate object. Returns: instance: Exchange rate object. """ exchange_rate = resp['exchange_rate'] exchange_rate_obj = ExchangeRate() exchange_rate_obj.set_exchange_rate_id(exchange_rate[\ 'exchange_rate_id']) exchange_rate_obj.set_currency_id(exchange_rate['currency_id']) exchange_rate_obj.set_currency_code(exchange_rate['currency_code']) exchange_rate_obj.set_effective_date(exchange_rate['effective_date']) exchange_rate_obj.set_rate(exchange_rate['rate']) return exchange_rate_obj def get_taxes(self, resp): """This method parses the given response and returns tax list object. Args: resp(dict): Response containing json object for taxes. Returns: instance: Tax list object. """ tax_list = TaxList() for value in resp['taxes']: tax = Tax() tax.set_tax_id(value['tax_id']) tax.set_tax_name(value['tax_name']) tax.set_tax_percentage(value['tax_percentage']) tax.set_tax_type(value['tax_type']) tax_list.set_taxes(tax) page_context = resp['page_context'] page_context_obj = PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) tax_list.set_page_context(page_context_obj) return tax_list def get_tax(self, resp): """This method parses the given response and returns tax object. Args: resp(dict): Response containing json object for tax. Returns: instance: Tax object. """ tax_obj = Tax() tax = resp['tax'] tax_obj.set_tax_id(tax['tax_id']) tax_obj.set_tax_name(tax['tax_name']) tax_obj.set_tax_percentage(tax['tax_percentage']) tax_obj.set_tax_type(tax['tax_type']) return tax_obj def get_tax_group(self, resp): """This method parses the given response and returns Tax group object. Args: resp(dict): Response containing json object for tax group. Returns: instance: Tax group object. Raises: Books Exception: If status is not '200' or '201'. """ tax_group_obj = TaxGroup() tax_group = resp['tax_group'] tax_group_obj.set_tax_group_id(tax_group['tax_group_id']) tax_group_obj.set_tax_group_name(tax_group['tax_group_name']) tax_group_obj.set_tax_group_percentage(tax_group[\ 'tax_group_percentage']) for value in tax_group['taxes']: tax = Tax() tax.set_tax_id(value['tax_id']) tax.set_tax_name(value['tax_name']) tax.set_tax_percentage(value['tax_percentage']) tax.set_tax_type(value['tax_type']) tax_group_obj.set_taxes(tax) return tax_group_obj def get_opening_balance(self, resp): """This method parses the given response and returns opening balance object. Args: resp(dict): Response containing json object for opening balance. Returns: instance: Opening balance object. """ opening_balance_obj = OpeningBalance() opening_balance = resp['opening_balance'] opening_balance_obj.set_opening_balance_id(opening_balance[\ 'opening_balance_id']) opening_balance_obj.set_date(opening_balance['date']) for value in opening_balance['accounts']: accounts = Account() accounts.set_account_split_id(value['account_split_id']) accounts.set_account_id(value['account_id']) accounts.set_account_name(value['account_name']) accounts.set_debit_or_credit(value['debit_or_credit']) accounts.set_exchange_rate(value['exchange_rate']) accounts.set_currency_id(value['currency_id']) accounts.set_currency_code(value['currency_code']) accounts.set_bcy_amount(value['bcy_amount']) accounts.set_amount(value['amount']) opening_balance_obj.set_accounts(accounts) return opening_balance_obj def get_autoreminders(self, resp): """This method parses the given response and returns autoreminders list. Args: resp(dict): Response containing json object for autoreminders. Returns: instance: Reminder list object. """ autoreminders = AutoReminderList() for value in resp['autoreminders']: autoreminders_obj = Autoreminder() autoreminders_obj.set_autoreminder_id(value['autoreminder_id']) autoreminders_obj.set_is_enabled(value['is_enabled']) autoreminders_obj.set_notification_type(value['type']) autoreminders_obj.set_address_type(value['address_type']) autoreminders_obj.set_number_of_days(value['number_of_days']) autoreminders_obj.set_subject(value['subject']) autoreminders_obj.set_body(value['body']) autoreminders_obj.set_order(value['order']) autoreminders.set_auto_reminders(autoreminders_obj) return autoreminders def get_autoreminder(self, resp): """Get auto reminder. Args: resp(dict): Response containing json object for auto reminders object. Returns: instance: Auto reminders object. """ autoreminder = resp['autoreminder'] autoreminder_obj = Autoreminder() autoreminder_obj.set_autoreminder_id(autoreminder['autoreminder_id']) autoreminder_obj.set_is_enabled(autoreminder['is_enabled']) autoreminder_obj.set_notification_type(autoreminder['type']) autoreminder_obj.set_address_type(autoreminder['address_type']) autoreminder_obj.set_number_of_days(autoreminder['number_of_days']) autoreminder_obj.set_subject(autoreminder['subject']) autoreminder_obj.set_body(autoreminder['body']) placeholders_obj = PlaceHolder() placeholders = resp['placeholders'] for value in placeholders['Invoice']: invoice = Invoice() invoice.set_name(value['name']) invoice.set_value(value['value']) placeholders_obj.set_invoice(invoice) for value in placeholders['Customer']: customer = Customer() customer.set_name(value['name']) customer.set_value(value['value']) placeholders_obj.set_customer(customer) for value in placeholders['Organization']: organization = Organization() organization.set_value(value['value']) organization.set_name(value['name']) placeholders_obj.set_organization(organization) autoreminder_obj.set_placeholders(placeholders) return autoreminder_obj def get_manual_reminders(self, resp): """This method parses the given response and returns manual reminders list. Args: resp(dict): Response containing json object for manual reminders list. Returns: list of instance: List of manual reminders object. """ manual_reminders = ManualReminderList() for value in resp['manualreminders']: manual_reminder = ManualReminder() manual_reminder.set_manualreminder_id(value['manualreminder_id']) manual_reminder.set_type(value['type']) manual_reminder.set_subject(value['subject']) manual_reminder.set_body(value['body']) manual_reminder.set_cc_me(value['cc_me']) manual_reminders.set_manual_reminders(manual_reminder) return manual_reminders def get_manual_reminder(self, resp): """Get manual reminder. Args: resp(dict): Response containing json object for manual reminder. Returns: instance: Manual reminders object. """ manualreminder = resp['manualreminder'] manualreminder_obj = ManualReminder() manualreminder_obj.set_manualreminder_id(manualreminder[\ 'manualreminder_id']) manualreminder_obj.set_type(manualreminder['type']) manualreminder_obj.set_subject(manualreminder['subject']) manualreminder_obj.set_body(manualreminder['body']) manualreminder_obj.set_cc_me(manualreminder['cc_me']) placeholders = resp['placeholders'] placeholders_obj = PlaceHolder() for value in placeholders['Invoice']: invoice = Invoice() invoice.set_name(value['name']) invoice.set_value(value['value']) placeholders_obj.set_invoice(invoice) for value in placeholders['Customer']: customer = Customer() customer.set_name(value['name']) customer.set_value(value['value']) placeholders_obj.set_customer(customer) for value in placeholders['Organization']: organization = Organization() organization.set_name(value['name']) organization.set_value(value['value']) placeholders_obj.set_organization(organization) manualreminder_obj.set_placeholders(placeholders_obj) return manualreminder_obj
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/SettingsParser.py", "copies": "1", "size": "36459", "license": "mit", "hash": 7208344967437537000, "line_mean": 41.7922535211, "line_max": 81, "alpha_frac": 0.6406648564, "autogenerated": false, "ratio": 4.13320485205759, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.527386970845759, "avg_score": null, "num_lines": null }
#$Id$# from books.model.ProjectList import ProjectList from books.model.Project import Project from books.model.PageContext import PageContext from books.model.TaskList import TaskList from books.model.Task import Task from books.model.User import User from books.model.TimeEntryList import TimeEntryList from books.model.TimeEntry import TimeEntry from books.model.Comment import Comment from books.model.InvoiceList import InvoiceList from books.model.Invoice import Invoice from books.model.UserList import UserList from books.model.CommentList import CommentList class ProjectsParser: """This class is used to parse the json object for Projects.""" def get_projects_list(self, resp): """This method parses the given response and returns projects list object. Args: resp(dict): Response containing json object for projects. Returns: instance: Projects list object. """ projects_list = ProjectList() for value in resp['projects']: project = Project() project.set_project_id(value['project_id']) project.set_project_name(value['project_name']) project.set_customer_id(value['customer_id']) project.set_customer_name(value['customer_name']) project.set_description(value['description']) project.set_status(value['status']) project.set_billing_type(value['billing_type']) #project.set_rate(value['rate']) project.set_created_time(value['created_time']) projects_list.set_projects(project) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) projects_list.set_page_context(page_context_obj) return projects_list def get_project(self, resp): """This method parses the given response and returns projects object. Args: resp(dict): Dictionary containing json object for projects. Returns: instance: Projects object. """ project_obj = Project() project = resp['project'] project_obj.set_project_id(project['project_id']) project_obj.set_project_name(project['project_name']) project_obj.set_customer_id(project['customer_id']) project_obj.set_customer_name(project['customer_name']) project_obj.set_currency_code(project['currency_code']) project_obj.set_description(project['description']) project_obj.set_status(project['status']) project_obj.set_billing_type(project['billing_type']) project_obj.set_budget_type(project['budget_type']) project_obj.set_total_hours(project['total_hours']) project_obj.set_billed_hours(project['billed_hours']) project_obj.set_un_billed_hours(project['un_billed_hours']) project_obj.set_created_time(project['created_time']) for value in project['tasks']: task = Task() task.set_task_id(value['task_id']) task.set_task_name(value['task_name']) task.set_description(value['description']) task.set_rate(value['rate']) task.set_budget_hours(value['budget_hours']) task.set_total_hours(value['total_hours']) task.set_billed_hours(value['billed_hours']) task.set_un_billed_hours(value['un_billed_hours']) project_obj.set_tasks(task) for value in project['users']: user = User() user.set_user_id(value['user_id']) user.set_is_current_user(value['is_current_user']) user.set_user_name(value['user_name']) user.set_email(value['email']) user.set_user_role(value['user_role']) user.set_status(value['status']) user.set_rate(value['rate']) user.set_budget_hours(value['budget_hours']) user.set_total_hours(value['total_hours']) user.set_billed_hours(value['billed_hours']) user.set_un_billed_hours(value['un_billed_hours']) project_obj.set_users(user) return project_obj def get_message(self, resp): """This method parses the given response and returns string message. Args: resp(dict): Response containing json object for string message. Returns: str: Success message. """ return resp['message'] def get_tasks_list(self, resp): """This method parses the given response and returns tasks list object. Args: resp(dict): Response containing json object for tasks list. Returns: instance: Task list object. """ task_list = TaskList() for value in resp['task']: task = Task() task.set_project_id(value['project_id']) task.set_task_id(value['task_id']) task.set_currency_id(value['currency_id']) task.set_customer_id(value['customer_id']) task.set_task_name(value['task_name']) task.set_project_name(value['project_name']) task.set_customer_name(value['customer_name']) task.set_billed_hours(value['billed_hours']) task.set_log_time(value['log_time']) task.set_un_billed_hours(value['un_billed_hours']) task_list.set_tasks(task) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) task_list.set_page_context(page_context_obj) return task_list def get_task(self, resp): """This method parses the given response and returns task object. Args: resp(dict): Response containing json object for task. Returns: instance: Task object. """ task_obj = Task() task = resp['task'] task_obj.set_project_id(task['project_id']) task_obj.set_project_name(task['project_name']) task_obj.set_task_id(task['task_id']) task_obj.set_task_name(task['task_name']) task_obj.set_description(task['description']) task_obj.set_rate(task['rate']) return task_obj def get_users(self, resp): """This method parses the given response and returns list of users object. Args: resp(dict): Response containing json object for users list object. Returns: instance: Users list object. """ users = UserList() for value in resp['users']: user = User() user.set_user_id(value['user_id']) user.set_is_current_user(value['is_current_user']) user.set_user_name(value['user_name']) user.set_email(value['email']) user.set_user_role(value['user_role']) user.set_status(value['status']) user.set_rate(value['rate']) user.set_budget_hours(value['budget_hours']) users.set_users(user) return users def get_user(self, resp): """This method parses the given response and returns user object. Args: resp(dict): Response containing json object for user. Returns: instance: User object. """ user_obj = User() user = resp['user'] user_obj.set_project_id(user['project_id']) user_obj.set_user_id(user['user_id']) user_obj.set_is_current_user(user['is_current_user']) user_obj.set_user_name(user['user_name']) user_obj.set_email(user['email']) user_obj.set_user_role(user['user_role']) return user_obj def get_time_entries_list(self, resp): """This method parses the given response and returns time entries list object. Args: resp(dict): Response containing json object for time entries. Returns: instance: Time entries list object. """ time_entries_list = TimeEntryList() for value in resp['time_entries']: time_entry = TimeEntry() time_entry.set_time_entry_id(value['time_entry_id']) time_entry.set_project_id(value['project_id']) time_entry.set_project_name(value['project_name']) time_entry.set_customer_id(value['customer_id']) time_entry.set_customer_name(value['customer_name']) time_entry.set_task_id(value['task_id']) time_entry.set_task_name(value['task_name']) time_entry.set_user_id(value['user_id']) time_entry.set_is_current_user(value['is_current_user']) time_entry.set_user_name(value['user_name']) time_entry.set_log_date(value['log_date']) time_entry.set_begin_time(value['begin_time']) time_entry.set_end_time(value['end_time']) time_entry.set_log_time(value['log_time']) time_entry.set_billed_status(value['billed_status']) time_entry.set_notes(value['notes']) time_entry.set_timer_started_at(value['timer_started_at']) time_entry.set_timer_duration_in_minutes(value[\ 'timer_duration_in_minutes']) time_entry.set_created_time(value['created_time']) time_entries_list.set_time_entries(time_entry) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) time_entries_list.set_page_context(page_context_obj) return time_entries_list def get_time_entry(self, resp): """This method parses the given response and returns time entry object. Args: resp(dict):Response containing json object for time entry. Returns: instance: Time entry object """ time_entry = resp['time_entry'] time_entry_obj = TimeEntry() time_entry_obj.set_time_entry_id(time_entry['time_entry_id']) time_entry_obj.set_project_id(time_entry['project_id']) time_entry_obj.set_project_name(time_entry['project_name']) time_entry_obj.set_task_id(time_entry['task_id']) time_entry_obj.set_task_name(time_entry['task_name']) time_entry_obj.set_user_id(time_entry['user_id']) time_entry_obj.set_user_name(time_entry['user_name']) time_entry_obj.set_is_current_user(time_entry['is_current_user']) time_entry_obj.set_log_date(time_entry['log_date']) time_entry_obj.set_begin_time(time_entry['begin_time']) time_entry_obj.set_end_time(time_entry['end_time']) time_entry_obj.set_log_time(time_entry['log_time']) time_entry_obj.set_billed_status(time_entry['billed_status']) time_entry_obj.set_notes(time_entry['notes']) time_entry_obj.set_timer_started_at(time_entry['timer_started_at']) time_entry_obj.set_timer_duration_in_minutes(time_entry[\ 'timer_duration_in_minutes']) time_entry_obj.set_created_time(time_entry['created_time']) return time_entry_obj def get_comments(self, resp): """This method parses the given response and returns comments list object. Args: resp(dict): Response containing json object for comments list. Returns: list of instance: Comments list object. """ comments = CommentList() for value in resp['comments']: comment = Comment() comment.set_comment_id(value['comment_id']) comment.set_project_id(value['project_id']) comment.set_description(value['description']) comment.set_commented_by_id(value['commented_by_id']) comment.set_commented_by(value['commented_by']) comment.set_is_current_user(value['is_current_user']) comment.set_date(value['date']) comment.set_date_description(value['date_description']) comment.set_time(value['time']) comments.set_comments(comment) return comments def get_comment(self, resp): """This method parses the given response and returns comment object. Args: resp(dict): Response containing json object for comment object. Returns: instance: Comment object. """ comment = resp['comment'] comment_obj = Comment() comment_obj.set_comment_id(comment['comment_id']) comment_obj.set_project_id(comment['project_id']) comment_obj.set_description(comment['description']) comment_obj.set_commented_by_id(comment['commented_by_id']) comment_obj.set_commented_by(comment['commented_by']) comment_obj.set_date(comment['date']) comment_obj.set_date_description(comment['date_description']) comment_obj.set_time(comment['time']) return comment_obj def get_invoice_list(self, resp): """This method parses the given response and returns invoice list object. Args: resp(dict): Response containing json object for invoice list object. Returns: instance: Invoice list object. """ invoices = InvoiceList() for value in resp['invoices']: invoice = Invoice() invoice.set_invoice_id(value['invoice_id']) invoice.set_customer_name(value['customer_name']) invoice.set_customer_id(value['customer_id']) invoice.set_status(value['status']) invoice.set_invoice_number(value['invoice_number']) invoice.set_reference_number(value['reference_number']) invoice.set_date(value['date']) invoice.set_due_date(value['due_date']) invoice.set_total(value['total']) invoice.set_balance(value['balance']) invoice.set_created_time(value['created_time']) invoices.set_invoices(invoice) page_context = resp['page_context'] page_context_obj = PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) invoices.set_page_context(page_context) return invoices
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/ProjectsParser.py", "copies": "1", "size": "15797", "license": "mit", "hash": 5269868867595870000, "line_mean": 39.9248704663, "line_max": 79, "alpha_frac": 0.6106222701, "autogenerated": false, "ratio": 3.8642367906066535, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9957421923549504, "avg_score": 0.0034874274314298384, "num_lines": 386 }
#$Id$# from books.model.RecurringExpense import RecurringExpense from books.model.RecurringExpenseList import RecurringExpenseList from books.model.Expense import Expense from books.model.ExpenseList import ExpenseList from books.model.Comment import Comment from books.model.PageContext import PageContext from books.model.CommentList import CommentList class RecurringExpensesParser: """This class is used to parse the json for recurring expenses. """ def get_list(self, resp): """This method parses the given response and returns recurring expenses list object. Args: resp(dict): Response containing json object for recurring expenses list. Returns: instance: Recurring expenses list object. """ recurring_expenses_list = RecurringExpenseList() for value in resp['recurring_expenses']: recurring_expenses = RecurringExpense() recurring_expenses.set_recurring_expense_id(\ value['recurring_expense_id']) recurring_expenses.set_recurrence_name(value['recurrence_name']) recurring_expenses.set_recurrence_frequency(\ value['recurrence_frequency']) recurring_expenses.set_repeat_every(value['repeat_every']) recurring_expenses.set_last_created_date(\ value['last_created_date']) recurring_expenses.set_next_expense_date(\ value['next_expense_date']) recurring_expenses.set_account_name(value['account_name']) recurring_expenses.set_paid_through_account_name(\ value['paid_through_account_name']) recurring_expenses.set_description(value['description']) recurring_expenses.set_currency_id(value['currency_id']) recurring_expenses.set_currency_code(value['currency_code']) recurring_expenses.set_total(value['total']) recurring_expenses.set_is_billable(value['is_billable']) recurring_expenses.set_customer_name(value['customer_name']) recurring_expenses.set_vendor_name(value['vendor_name']) recurring_expenses.set_status(value['status']) recurring_expenses.set_created_time(value['created_time']) recurring_expenses_list.set_recurring_expenses(recurring_expenses) page_context = resp['page_context'] page_context_obj = PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) recurring_expenses_list.set_page_context(page_context_obj) return recurring_expenses_list def get_recurring_expense(self, resp): """This method parses the given response and returns recurring expenses object. Args: resp(dict): Response containing json object for recurring expenses. Returns: instance: Recurring expenses object. """ recurring_expense = resp['recurring_expense'] recurring_expense_obj = RecurringExpense() recurring_expense_obj.set_recurring_expense_id(\ recurring_expense['recurring_expense_id']) recurring_expense_obj.set_recurrence_name(\ recurring_expense['recurrence_name']) recurring_expense_obj.set_start_date(recurring_expense['start_date']) recurring_expense_obj.set_end_date(recurring_expense['end_date']) recurring_expense_obj.set_recurrence_frequency(\ recurring_expense['recurrence_frequency']) recurring_expense_obj.set_repeat_every(\ recurring_expense['repeat_every']) recurring_expense_obj.set_last_created_date(\ recurring_expense['last_created_date']) recurring_expense_obj.set_next_expense_date(\ recurring_expense['next_expense_date']) recurring_expense_obj.set_account_id(recurring_expense['account_id']) recurring_expense_obj.set_account_name(\ recurring_expense['account_name']) recurring_expense_obj.set_paid_through_account_id(\ recurring_expense['paid_through_account_id']) recurring_expense_obj.set_paid_through_account_name(\ recurring_expense['paid_through_account_name']) recurring_expense_obj.set_vendor_id(recurring_expense['vendor_id']) recurring_expense_obj.set_vendor_name(recurring_expense['vendor_name']) recurring_expense_obj.set_currency_id(recurring_expense['currency_id']) recurring_expense_obj.set_currency_code(\ recurring_expense['currency_code']) recurring_expense_obj.set_exchange_rate(\ recurring_expense['exchange_rate']) recurring_expense_obj.set_tax_id(recurring_expense['tax_id']) recurring_expense_obj.set_tax_name(recurring_expense['tax_name']) recurring_expense_obj.set_tax_percentage(\ recurring_expense['tax_percentage']) recurring_expense_obj.set_tax_amount(recurring_expense['tax_amount']) recurring_expense_obj.set_sub_total(recurring_expense['sub_total']) recurring_expense_obj.set_total(recurring_expense['total']) recurring_expense_obj.set_bcy_total(recurring_expense['bcy_total']) recurring_expense_obj.set_amount(recurring_expense['amount']) recurring_expense_obj.set_description(recurring_expense['description']) recurring_expense_obj.set_is_inclusive_tax(\ recurring_expense['is_inclusive_tax']) recurring_expense_obj.set_is_billable(recurring_expense['is_billable']) recurring_expense_obj.set_customer_id(recurring_expense['customer_id']) recurring_expense_obj.set_customer_name(\ recurring_expense['customer_name']) recurring_expense_obj.set_status(recurring_expense['status']) recurring_expense_obj.set_created_time(\ recurring_expense['created_time']) recurring_expense_obj.set_last_modified_time(\ recurring_expense['last_modified_time']) recurring_expense_obj.set_project_id(recurring_expense['project_id']) recurring_expense_obj.set_project_name(\ recurring_expense['project_name']) return recurring_expense_obj def get_message(self, response): """This method parses the json object and returns the message string. Args: response(dict): Response containing json object for message. Returns: str: Success message. """ return response['message'] def get_expense_history(self, resp): """This method parses the json object and returns expense history list. Args: resp(dict): Response containing json object for expense history. Returns: instance: Expenses list object. """ expenses_list = ExpenseList() for value in resp['expensehistory']: expense = Expense() expense.set_expense_id(value['expense_id']) expense.set_date(value['date']) expense.set_account_name(value['account_name']) expense.set_vendor_name(value['vendor_name']) expense.set_paid_through_account_name(\ value['paid_through_account_name']) expense.set_customer_name(value['customer_name']) expense.set_total(value['total']) expense.set_status(value['status']) expenses_list.set_expenses(expense) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) expenses_list.set_page_context(page_context_obj) return expenses_list def get_comments(self, resp): """This method parses the given response and returns comments list. Args: resp(dict): Response containing comments list. Returns: instance: Comments List object. """ comments_list = CommentList() for value in resp['comments']: comment = Comment() comment.set_comment_id(value['comment_id']) comment.set_recurring_expense_id(value['recurring_expense_id']) comment.set_description(value['description']) comment.set_commented_by_id(value['commented_by_id']) comment.set_commented_by(value['commented_by']) comment.set_date(value['date']) comment.set_date_description(value['date_description']) comment.set_time(value['time']) comment.set_operation_type(value['operation_type']) comment.set_transaction_id(value['transaction_id']) comment.set_transaction_type(value['transaction_type']) comments_list.set_comments(comment) return comments_list
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/RecurringExpensesParser.py", "copies": "1", "size": "9494", "license": "mit", "hash": 3822844759456556500, "line_mean": 46, "line_max": 79, "alpha_frac": 0.6558879292, "autogenerated": false, "ratio": 3.9069958847736626, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5062883813973662, "avg_score": null, "num_lines": null }
#$Id$# from books.model.RecurringExpense import RecurringExpense from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") recurring_expenses_api = zoho_books.get_recurring_expenses_api() recurring_expense_id = recurring_expenses_api.get_recurring_expenses().get_recurring_expenses()[0].get_recurring_expense_id() accounts_api = zoho_books.get_bank_accounts_api() account_id = accounts_api.get_bank_accounts().get_bank_accounts()[0].get_account_id() param = {'filter_by': 'AccountType.Expense'} chart_of_accounts_api = zoho_books.get_chart_of_accounts_api() expense_account_id = chart_of_accounts_api.get_chart_of_accounts(param).get_chartofaccounts()[1].get_account_id() settings_api = zoho_books.get_settings_api() currency_id = settings_api.get_currencies().get_currencies()[0].get_currency_id() contact_api = zoho_books.get_contacts_api() customer_id = contact_api.get_contacts().get_contacts()[0].get_contact_id() vendor_api = zoho_books.get_vendor_payments_api() vendor_id = vendor_api.get_vendor_payments().get_vendor_payments()[0].get_vendor_id() # list recurring expenses print recurring_expenses_api.get_recurring_expenses() # get a recurring expense print recurring_expenses_api.get(recurring_expense_id) # create a recurring expense recurring_expense=RecurringExpense() recurring_expense.set_account_id(expense_account_id) recurring_expense.set_paid_through_account_id(account_id) recurring_expense.set_recurrence_name('prabu') recurring_expense.set_start_date('2014-01-10') recurring_expense.set_end_date('') recurring_expense.set_recurrence_frequency('weeks') recurring_expense.set_repeat_every(2) recurring_expense.set_amount(100.0) recurring_expense.set_tax_id("") recurring_expense.set_is_inclusive_tax(True) #recurring_expense.set_is_billable() recurring_expense.set_customer_id(customer_id) recurring_expense.set_vendor_id(vendor_id) recurring_expense.set_project_id('') recurring_expense.set_currency_id(currency_id) recurring_expense.set_exchange_rate(1) print recurring_expenses_api.create(recurring_expense) # Update a recurring expense recurring_expense=RecurringExpense() recurring_expense.set_account_id(expense_account_id) recurring_expense.set_paid_through_account_id(account_id) recurring_expense.set_recurrence_name('vintu') recurring_expense.set_start_date('2014-01-10') recurring_expense.set_end_date('') recurring_expense.set_recurrence_frequency('weeks') recurring_expense.set_repeat_every(2) recurring_expense.set_amount(100.0) recurring_expense.set_tax_id("") recurring_expense.set_is_inclusive_tax(True) #recurring_expense.set_is_billable() recurring_expense.set_customer_id(customer_id) recurring_expense.set_vendor_id(vendor_id) recurring_expense.set_project_id('') recurring_expense.set_currency_id(currency_id) recurring_expense.set_exchange_rate(1) print recurring_expenses_api.update(recurring_expense_id,recurring_expense) # Delete a recurring expense print recurring_expenses_api.delete(recurring_expense_id) # Stop a recurring expense print recurring_expenses_api.stop_recurring_expense(recurring_expense_id) # Resume a recurring expense print recurring_expenses_api.resume_recurring_expense(recurring_expense_id) # list child expenses created date='date' print recurring_expenses_api.list_child_expenses_created(recurring_expense_id) print recurring_expenses_api.list_child_expenses_created(recurring_expense_id,date) # list recurring expense comments and history print recurring_expenses_api.list_recurring_expense_comments_and_history(recurring_expense_id)
{ "repo_name": "zoho/books-python-wrappers", "path": "test/RecurringExpensesTest.py", "copies": "1", "size": "3584", "license": "mit", "hash": 9171299825506829000, "line_mean": 34.4851485149, "line_max": 125, "alpha_frac": 0.79296875, "autogenerated": false, "ratio": 2.9185667752442996, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.9140547817704685, "avg_score": 0.014197541507922783, "num_lines": 101 }
#$Id$# from books.model.RecurringInvoice import RecurringInvoice from books.model.RecurringInvoiceList import RecurringInvoiceList from books.model.PageContext import PageContext from books.model.LineItem import LineItem from books.model.CustomField import CustomField from books.model.Address import Address from books.model.PaymentGateway import PaymentGateway from books.model.Comment import Comment from books.model.CommentList import CommentList class RecurringInvoiceParser: """This class is used to parse the json for Recurring invoice.""" def recurring_invoices(self, response): """This method parses the given response and creates recurring invoices list object. Args: response(dict): Response containing json object for recurring invoice list. Returns: instance: Recurring invoice list object. """ recurring_invoices_list = RecurringInvoiceList() recurring_invoices = [] for value in response['recurring_invoices']: recurring_invoice = RecurringInvoice() recurring_invoice.set_recurring_invoice_id(\ value['recurring_invoice_id']) recurring_invoice.set_recurrence_name(value['recurrence_name']) recurring_invoice.set_status(value['status']) recurring_invoice.set_total(value['total']) recurring_invoice.set_customer_id(value['customer_id']) recurring_invoice.set_customer_name(value['customer_name']) recurring_invoice.set_start_date(value['start_date']) recurring_invoice.set_end_date(value['end_date']) recurring_invoice.set_last_sent_date(value['last_sent_date']) recurring_invoice.set_next_invoice_date(value['next_invoice_date']) recurring_invoice.set_recurrence_frequency(\ value['recurrence_frequency']) recurring_invoice.set_repeat_every(value['repeat_every']) recurring_invoice.set_created_time(value['created_time']) recurring_invoice.set_last_modified_time(\ value['last_modified_time']) recurring_invoices.append(recurring_invoice) recurring_invoices_list.set_recurring_invoices(recurring_invoices) page_context = response['page_context'] page_context_obj = PageContext() page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) recurring_invoices_list.set_page_context(page_context_obj) return recurring_invoices_list def recurring_invoice(self, response): """This method parses the response and creates recurring invoice object. Args: response(dict): Response containing json object for recurring invoice. Returns: instance: Recurring invoice object. """ recurring_invoice = response['recurring_invoice'] recurring_invoice_obj = RecurringInvoice() recurring_invoice_obj.set_recurring_invoice_id(\ recurring_invoice['recurring_invoice_id']) recurring_invoice_obj.set_recurrence_name(\ recurring_invoice['recurrence_name']) recurring_invoice_obj.set_status(recurring_invoice['status']) recurring_invoice_obj.set_recurrence_frequency(\ recurring_invoice['recurrence_frequency']) recurring_invoice_obj.set_repeat_every(\ recurring_invoice['repeat_every']) recurring_invoice_obj.set_start_date(recurring_invoice['start_date']) recurring_invoice_obj.set_end_date(recurring_invoice['end_date']) recurring_invoice_obj.set_last_sent_date(\ recurring_invoice['last_sent_date']) recurring_invoice_obj.set_next_invoice_date(\ recurring_invoice['next_invoice_date']) recurring_invoice_obj.set_payment_terms(\ recurring_invoice['payment_terms']) recurring_invoice_obj.set_payment_terms_label(\ recurring_invoice['payment_terms_label']) recurring_invoice_obj.set_customer_id(recurring_invoice['customer_id']) recurring_invoice_obj.set_customer_name(\ recurring_invoice['customer_name']) recurring_invoice_obj.set_contact_persons(\ recurring_invoice['contact_persons']) recurring_invoice_obj.set_currency_id(recurring_invoice['currency_id']) recurring_invoice_obj.set_price_precision(\ recurring_invoice['price_precision']) recurring_invoice_obj.set_currency_code(\ recurring_invoice['currency_code']) recurring_invoice_obj.set_currency_symbol(\ recurring_invoice['currency_symbol']) recurring_invoice_obj.set_exchange_rate(\ recurring_invoice['exchange_rate']) recurring_invoice_obj.set_discount(recurring_invoice['discount']) recurring_invoice_obj.set_is_discount_before_tax(\ recurring_invoice['is_discount_before_tax']) recurring_invoice_obj.set_discount_type(\ recurring_invoice['discount_type']) line_items = [] for value in recurring_invoice['line_items']: line_item = LineItem() line_item.set_item_id(value['item_id']) line_item.set_line_item_id(value['line_item_id']) line_item.set_name(value['name']) line_item.set_description(value['description']) line_item.set_item_order(value['item_order']) line_item.set_rate(value['rate']) line_item.set_quantity(value['quantity']) line_item.set_unit(value['unit']) line_item.set_discount_amount(value['discount_amount']) line_item.set_discount(value['discount']) line_item.set_tax_id(value['tax_id']) line_item.set_tax_name(value['tax_name']) line_item.set_tax_type(value['tax_type']) line_item.set_tax_percentage(value['tax_percentage']) line_item.set_item_total(value['item_total']) line_items.append(line_item) recurring_invoice_obj.set_line_items(line_items) recurring_invoice_obj.set_shipping_charge(\ recurring_invoice['shipping_charge']) recurring_invoice_obj.set_adjustment(recurring_invoice['adjustment']) recurring_invoice_obj.set_adjustment_description(\ recurring_invoice['adjustment_description']) recurring_invoice_obj.set_late_fee(recurring_invoice['late_fee']) recurring_invoice_obj.set_sub_total(recurring_invoice['sub_total']) recurring_invoice_obj.set_total(recurring_invoice['total']) recurring_invoice_obj.set_tax_total(recurring_invoice['tax_total']) recurring_invoice_obj.set_allow_partial_payments(\ recurring_invoice['allow_partial_payments']) taxes = [] for value in recurring_invoice['taxes']: tax = Tax() tax.set_tax_name(value['tax_name']) tax.set_tax_amount['value_tax_amount'] taxes.append(tax) recurring_invoice_obj.set_taxes(taxes) custom_fields = [] for value in recurring_invoice['custom_fields']: custom_field = CustomField() custom_field.set_index(value['index']) custom_field.set_value(value['value']) custom_fields.append(custom_field) recurring_invoice_obj.set_custom_fields(custom_fields) payment_gateways = recurring_invoice['payment_options'][\ 'payment_gateways'] for value in payment_gateways: payment_gateway = PaymentGateway() payment_gateway.set_configured(value['configured']) payment_gateway.set_additional_field1(value['additional_field1']) payment_gateway.set_gateway_name(value['gateway_name']) recurring_invoice_obj.set_payment_options(payment_gateway) billing_address = recurring_invoice['billing_address'] billing_address_obj = Address() billing_address_obj.set_address(billing_address['address']) billing_address_obj.set_city(billing_address['city']) billing_address_obj.set_state(billing_address['state']) billing_address_obj.set_zip(billing_address['zip']) billing_address_obj.set_country(billing_address['country']) billing_address_obj.set_fax(billing_address['fax']) recurring_invoice_obj.set_billing_address(billing_address_obj) shipping_address = recurring_invoice['shipping_address'] shipping_address_obj = Address() shipping_address_obj.set_address(shipping_address['address']) shipping_address_obj.set_city(shipping_address['city']) shipping_address_obj.set_state(shipping_address['state']) shipping_address_obj.set_zip(shipping_address['zip']) shipping_address_obj.set_country(shipping_address['country']) shipping_address_obj.set_fax(shipping_address['fax']) recurring_invoice_obj.set_shipping_address(shipping_address_obj) recurring_invoice_obj.set_template_id(recurring_invoice['template_id']) recurring_invoice_obj.set_template_name(\ recurring_invoice['template_name']) recurring_invoice_obj.set_notes(recurring_invoice['notes']) recurring_invoice_obj.set_terms(recurring_invoice['terms']) recurring_invoice_obj.set_salesperson_id(\ recurring_invoice['salesperson_id']) recurring_invoice_obj.set_salesperson_name(\ recurring_invoice['salesperson_name']) recurring_invoice_obj.set_created_time(\ recurring_invoice['created_time']) recurring_invoice_obj.set_last_modified_time(\ recurring_invoice['last_modified_time']) return recurring_invoice_obj def get_message(self, response): """This method parses the json object and returns the message string. Args: response(dict): Response containing json object. Returns: string: Success message. """ return response['message'] def recurring_invoice_history_list(self, response): """This method parses the json object and returns list of comments object. Args: response(dict): Response containing json object. Returns: instance: Comments list object. """ comments = CommentList() for value in response['comments']: comment = Comment() comment.set_comment_id(value['comment_id']) comment.set_recurring_invoice_id(value['recurring_invoice_id']) comment.set_description(value['description']) comment.set_commented_by_id(value['commented_by_id']) comment.set_commented_by(value['commented_by']) comment.set_comment_type(value['comment_type']) comment.set_date(value['date']) comment.set_date_description(value['date_description']) comment.set_time(value['time']) comment.set_operation_type(value['operation_type']) comment.set_transaction_id(value['transaction_id']) comment.set_transaction_type(value['transaction_type']) comments.set_comments(comment) return comments
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/RecurringInvoiceParser.py", "copies": "1", "size": "11648", "license": "mit", "hash": -5393979276851637000, "line_mean": 46.737704918, "line_max": 79, "alpha_frac": 0.6528159341, "autogenerated": false, "ratio": 3.9986268451767937, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0159651510670342, "num_lines": 244 }
#$Id$ from books.model.Term import Term from books.model.AddressFormat import AddressFormat class Preference: """This class is used to create object for preferences.""" def __init__(self): """Initialize parameters for Preferences object.""" self.convert_to_invoice = None self.attach_pdf_for_email = '' self.estimate_approval_status = '' self.notify_me_on_online_payment = None self.send_payment_receipt_acknowledgement = None self.auto_notify_recurring_invoice = None self.snail_mail_include_payment_stub = None self.is_show_powered_by = None self.attach_expense_receipt_to_invoice = None self.is_estimate_enabled = None self.is_project_enabled = None self.is_purchaseorder_enabled = None self.is_salesorder_enabled = None self.is_salesorder_enabled = None self.is_pricebooks_enabled = None self.attach_payment_receipt_with_acknowledgement = None self.auto_reminders = [] self.terms = Term() self.address_formats = AddressFormat() self.allow_auto_categorize = '' def set_allow_auto_categorize(self, allow_auto_categorize): """Set allow auto categorize. Args: allow_auto_categorize(str): Allow auto categorize. """ self.allow_auto_categorize = allow_auto_categorize def get_allow_auto_categorize(self): """Get allow auto categorize. Returns: str: Allow auto categorize. """ return self.allow_auto_categorize def set_convert_to_invoice(self, convert_to_invoice): """Set whether to convert to invoice. Args: convert_to_invoice(bool): True to Convert to invoice else False. """ self.convert_to_invoice = convert_to_invoice def get_convert_to_invoice(self): """Get whether to convert to invoice. Returns: bool: True to Convert to invoice else false. """ return self.convert_to_invoice def set_attach_pdf_for_email(self, attach_pdf_for_email): """Set whether to attach pdf for email. Args: attach_pdf_for_email(bool): True to attach pdf for email. """ self.attach_pdf_for_email = attach_pdf_for_email def get_attach_pdf_for_email(self): """Get whether to attach pdf for email. Returns: bool: True to attach pdf for email. """ return self.attach_pdf_for_email def set_estimate_approval_status(self, estimate_approval_status): """Set estimate approval status. Args: estimate_approval_status(bool): Estimate approval status. """ self.estimate_approval_status = estimate_approval_status def get_estimate_approval_status(self): """Get estimate approval status. Returns: bool: Estimate approval status. """ return self.estimate_approval_status def set_notify_me_on_online_payment(self, notify_me_on_online_payment): """Set whether to notify me on online payment. Args: notify_me_on_online(bool): True to notify online payment else false. """ self.notify_me_on_online_payment = notify_me_on_online_payment def get_notify_me_on_online_payment(self): """Get whether to notify me on online payment. Returns: bool: True to notify online payment else False. """ return self.notify_me_on_online_payment def set_send_payment_receipt_acknowledgement(self, \ send_payment_receipt_acknowledgement): """Set whether to send payment receipt acknowledgement. Args: send_payment_receipt_acknowledgement(bool): True to send payment receipt acknowledgemnt else False. """ self.send_payment_receipt_acknowledgement = \ send_payment_receipt_acknowledgement def get_send_payment_receipt_acknowledgement(self): """Get whether to send payment receipt acknowledgement. Returns: bool: True to send payment receipt acknowledgemnt else False. """ return self.send_payment_receipt_acknowledgement def set_auto_notify_recurring_invoice(self, auto_notify_recurring_invoice): """Set whether to notify invoice automatically or not. Args: auto_notify_recurring_invoice(bool): True to auto notify recurring invoice else false. """ self.auto_notify_recurring_invoice = auto_notify_recurring_invoice def get_auto_notify_recurring_invoice(self): """Get whether to notify invoice automatically or not. Returns: bool: True if auto notify is enabled else false. """ return self.auto_notify_recurring_invoice def set_snail_mail_include_payment_stub(self, \ snail_mail_include_payment_stub): """Set snail mail include payment stub. Args: snail_mail_include_payment_stub(bool): Snail mail paymanet stub. """ self.snail_mail_include_payment_stub = snail_mail_include_payment_stub def get_snail_mail_include_payment_stub(self): """Get snail mail payment include stub. Returns: bool: Snail mail payment include stub. """ return self.snail_mail_include_payment_stub def set_is_show_powered_by(self, is_show_powered_by): """Set whether to show powered by. Args: is_show_powered_by(bool): True to show powered by. """ self.is_show_powered_by = is_show_powered_by def get_is_show_powered_by(self): """Get whether to show powered by. Returns: bool: True to show powered by else false. """ return self.is_show_powered_by def set_attach_expense_receipt_to_invoice(self, attach_receipt_to_invoice): """Set whether to attach receipt to invoice. Args: attach_receipt_to_invoice(bool): True to attach receipt to invoice. """ self.attach_expense_receipt_to_invoice = attach_receipt_to_invoice def get_attach_expense_receipt_to_invoice(self): """Get whether to attach receipt to invoice. Returns: bool: True to attach receipt to invoice. """ return self.attach_expense_receipt_to_invoice def set_is_estimate_enabled(self, is_estimate_enabled): """Set whether to enable estimate or not. Args: is_estimate_enabled(bool): True to enable estimate else False. """ self.is_estimate_enabled = is_estimate_enabled def get_is_estimate_enabled(self): """Get whether to enable estimate or not. Returns: bool: True to enable estimate else false. """ return self.is_estimate_enabled def set_is_project_enabled(self, is_project_enabled): """Set whether to enable project or not. Args: is_project_enabled(bool): True to enable project else False. """ self.is_project_enabled = is_project_enabled def get_is_project_enabled(self): """Get whether to enable project or not. Returns: bool: True to enable project else False. """ return self.is_project_enabled def set_is_purchaseorder_enabled(self, is_purchaseorder_enabled): """Set whether is purchaseorder enabled. Args: is_purchaseorder_enabled(bool):True if purchase order is enabled else false. """ self.is_purchaseorder_enabled = is_purchaseorder_enabled def get_is_purchaseorder_enabled(self): """Get whether is purchase order enabled. Returns: bool: True if purchase order is enabled else false. """ return self.is_purchaseorder_enabled def set_is_salesorder_enabled(self, is_salesorder_enabled): """Set whether salesorder is enabled. Args: is_salesorder_enabled(bool): True if salesorder is enabled else false. """ self.is_salesorder_enabled = is_salesorder_enabled def get_is_salesorder_enabled(self): """Get whether salesorder is enabled. Returns: bool: True if sales order is enabled else false. """ return self.is_salesorder_enabled def set_is_pricebooks_enabled(self, is_pricebooks_enabled): """Set is pricebooks enabled. Args: is_pricebooks_enabled(bool): True if pricebooks is enabled else false. """ self.is_pricebooks_enabled = is_pricebooks_enabled def get_is_pricebooks_enabled(self): """Get is pricebooks enabled. Returns: bool: True if price books is enabled else false. """ return self.is_pricebooks_enabled def set_attach_payment_receipt_with_acknowledgement(self, \ attach_payment_receipt_with_acknowledgement): """Set attachpayment receipt with acknowledgemnt. Args: attach_payment_receipt_with_acknowledgement(bool): True to attach payment receipt with acknowledgemnt. """ self.attach_payment_receipt_with_acknowledgement = \ attach_payment_receipt_with_acknowledgement def get_attach_payment_receipt_with_acknowledgemnt(self): """Get attach payment receipt with acknowledgement. Returns: bool: True to attach payment receipt with acknowledgment. """ return self.attach_payment_receipt_with_acknowledgement def set_auto_reminders(self, auto_reminder): """Set auto reminders. Args: auto_reminder(instance): Auto reminders. """ self.auto_reminders.append(auto_reminder) def get_auto_reminders(self): """Get auto reminders. Returns: list of instance: List of auto reminder object. """ return self.auto_reminders def set_terms(self, term): """Set terms. Args: term(instance): Terms object. """ self.terms = term def get_terms(self): """Get terms. Returns: instance: Term object. """ return self.terms def set_address_formats(self, address_formats): """Set address formats. Args: address_formats(instance): Address Formats. """ self.address_formats = address_formats def get_address_formats(self): """Get address formats. Returns: instance: Address formats. """ return self.address_formats def to_json(self): """This method is used to convert preference object to json format. Returns: dict: Dictionary containing json object for preferences. """ data = {} if self.convert_to_invoice is not None: data['convert_to_invoice'] = self.convert_to_invoice if self.notify_me_on_online_payment is not None: data['notify_me_on_online_payment'] = \ self.notify_me_on_online_payment if self.send_payment_receipt_acknowledgement is not None: data['send_payment_receipt_acknowledgement'] = \ self.send_payment_receipt_acknowledgement if self.auto_notify_recurring_invoice is not None: data['auto_notify_recurring_invoice'] = \ self.auto_notify_recurring_invoice if self.snail_mail_include_payment_stub != None: data['snail_mail_include_payment_stub'] = \ self.snail_mail_include_payment_stub if self.is_show_powered_by != None: data['is_show_powered_by'] = self.is_show_powered_by if self.attach_expense_receipt_to_invoice != None: data['attach_expense_receipt_to_invoice'] = \ self.attach_expense_receipt_to_invoice if self.is_estimate_enabled != None: data['is_estimate_enabled'] = self.is_estimate_enabled if self.is_project_enabled != None: data['is_project_enabled'] = self.is_project_enabled return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Preference.py", "copies": "1", "size": "12396", "license": "mit", "hash": 5791061040595580000, "line_mean": 28.8698795181, "line_max": 79, "alpha_frac": 0.6110842207, "autogenerated": false, "ratio": 4.168123739071957, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5279207959771957, "avg_score": null, "num_lines": null }
#$Id$# from books.model.Transaction import Transaction from books.model.CreditNoteRefund import CreditNoteRefund from books.model.VendorPayment import VendorPayment from books.model.CustomerPayment import CustomerPayment from books.model.Bill import Bill from books.model.Expense import Expense from books.model.Invoice import Invoice from books.service.ZohoBooks import ZohoBooks zoho_books = ZohoBooks("{auth_token}", "{organization_id}") bank_transaction_api = zoho_books.get_bank_transactions_api() accounts_api = zoho_books.get_bank_accounts_api() account_id = accounts_api.get_bank_accounts().get_bank_accounts()[1].get_account_id() transaction_type = 'sales_without_invoices' transaction_id = bank_transaction_api.get_bank_transactions().get_transactions()[0].get_transaction_id() contact_api = zoho_books.get_contacts_api() customer_id = contact_api.get_contacts().get_contacts()[0].get_contact_id() settings_api = zoho_books.get_settings_api() currency_id = settings_api.get_currencies().get_currencies()[0].get_currency_id() vendor_payments_api = zoho_books.get_vendor_payments_api() payment_id = vendor_payments_api.get_vendor_payments().get_vendor_payments()[0].get_payment_id() vendor_id = vendor_payments_api.get_vendor_payments().get_vendor_payments()[0].get_vendor_id() bill_api = zoho_books.get_bills_api() bill_id = bill_api.get_bills().get_bills()[1].get_bill_id() # get transaction list param={'account_id':account_id} print bank_transaction_api.get_bank_transactions(param) print bank_transaction_api.get_bank_transactions() # get transaction ''' print bank_transaction_api.get("71127000000224005") ''' # Create a transaction for an account bank_transaction=Transaction() bank_transaction.set_from_account_id('71127000000079023') bank_transaction.set_to_account_id('71127000000012001') bank_transaction.set_transaction_type('transfer_fund') bank_transaction.set_amount(10.0) bank_transaction.set_payment_mode('cash') bank_transaction.set_exchange_rate(10.0) bank_transaction.set_date('2014-02-01') bank_transaction.set_customer_id(customer_id) bank_transaction.set_reference_number('') bank_transaction.set_description('halo') bank_transaction.set_currency_id(currency_id) print bank_transaction_api.create(bank_transaction) # update a transaction bank_transaction=Transaction() bank_transaction.set_from_account_id('71127000000079023') bank_transaction.set_to_account_id('71127000000012001') bank_transaction.set_transaction_type('transfer_fund') bank_transaction.set_amount(10.0) bank_transaction.set_payment_mode('cash') bank_transaction.set_exchange_rate(100.0) bank_transaction.set_date('2014-02-01') bank_transaction.set_customer_id(customer_id) bank_transaction.set_reference_number('') bank_transaction.set_description('halo') bank_transaction.set_currency_id(currency_id) print bank_transaction_api.update(transaction_id,bank_transaction) # Delete a transaction print bank_transaction_api.delete(transaction_id) # Get matching transactions #param = {'transaction_type':'expense' } print bank_transaction_api.get_matching_transactions(transaction_id) #print bank_transaction_api.get_matching_transactions(transaction_id,param) # Match a transaction transactions_to_be_matched = Transaction() transactions_to_be_matched.set_transaction_id(transaction_id) transactions_to_be_matched.set_transaction_type(transaction_type) transactions = [] transactions.append(transactions_to_be_matched) print bank_transaction_api.match_a_transaction(transaction_id,transactions) print bank_transaction_api.match_a_transaction(transaction_id,transactions, account_id) # Unmatch a matched transaction print bank_transaction_api.unmatch_a_matched_transaction(transaction_id) print bank_transaction_api.unmatch_a_matched_transaction(transaction_id,account_id) # Get associated transaction sort_column='statement_date' print bank_transaction_api.get_associated_transactions(transaction_id) print bank_transaction_api.get_associated_transactions(transaction_id,sort_column) # Exclude a transaction print bank_transaction_api.exclude_a_transaction(transaction_id) print bank_transaction_api.exclude_a_transaction(transaction_id, account_id) # Restore a transaction #print bank_transaction_api.restore_a_transaction(transaction_id) print bank_transaction_api.restore_a_transaction(transaction_id, account_id) ''' #------------------------------------------------------------------------ #Categorize ''' credit_notes_api = zoho_books.get_creditnotes_api() credit_note_id = credit_notes_api.get_credit_notes(param).get_creditnotes()[0].get_creditnote_id() # Categorize an uncategorized transaction categorize_a_transaction = Transaction() categorize_a_transaction.set_from_account_id('71127000000079023') categorize_a_transaction.set_to_account_id('71127000000012001') categorize_a_transaction.set_transaction_type('transfer_fund') categorize_a_transaction.set_amount(10.0) categorize_a_transaction.set_payment_mode('cash') categorize_a_transaction.set_exchange_rate(1.0) categorize_a_transaction.set_date('2014-04-29') categorize_a_transaction.set_customer_id(customer_id) categorize_a_transaction.set_reference_number('2') categorize_a_transaction.set_description('transafer') categorize_a_transaction.set_currency_id(currency_id) print bank_transaction_api.categorize_an_uncategorized_transaction(transaction_id,categorize_a_transaction) # Categorize as credit note refund refund = CreditNoteRefund() refund.set_creditnote_id(credit_note_id) refund.set_date('2014-01-01') refund.set_refund_mode('cash') refund.set_reference_number('') refund.set_exchange_rate(1.0) refund.set_from_account_id(account_id) refund.set_description('credit not categorize') print bank_transaction_api.categorize_as_credit_note_refunds(transaction_id,refund) # Categorize as vendor payments vendor_payment = VendorPayment() vendor_payment.set_vendor_id(vendor_id) bills=Bill() bills.set_bill_id(bill_id) bills.set_amount_applied(10.0) vendor_payment.set_bills(bills) vendor_payment.set_payment_mode('cash') vendor_payment.set_description('vendor payments') vendor_payment.set_date('2014-04-29') vendor_payment.set_reference_number('2') vendor_payment.set_exchange_rate(1.0) vendor_payment.set_amount(20.0) vendor_payment.set_paid_through_account_id('') print bank_transaction_api.categorize_as_vendor_payment(transaction_id,vendor_payment) # Categorize as customer payment invoice_api = zoho_books.get_invoices_api() invoice_id = invoice_api.get_invoices().get_invoices()[0].get_invoice_id() customer_payments = CustomerPayment() customer_payments.set_customer_id(customer_id) invoice = Invoice() invoice.set_invoice_id(invoice_id) invoice.set_amount_applied(20.0) invoice.set_tax_amount_withheld(4.0) invoices = [invoice] customer_payments.set_invoices(invoices) customer_payments.set_payment_mode('cash') customer_payments.set_description('') customer_payments.set_date('2014-04-28') customer_payments.set_reference_number('') customer_payments.set_exchange_rate(1.0) customer_payments.set_amount(10.0) customer_payments.set_bank_charges(0.0) customer_payments.set_tax_account_id('') customer_payments.set_account_id(account_id) contact_ids = contact_api.get_contacts().get_contacts()[1].get_contact_id() print bank_transaction_api.categorize_as_customer_payment(transaction_id,customer_payments) print bank_transaction_api.categorize_as_customer_payment(transaction_id,customer_payments,contact_ids) # Categorize as expense expense = Expense() expense.set_account_id(account_id) expense.set_paid_through_account_id('') expense.set_amount(200.0) expense.set_date('2014-04-28') expense.set_is_inclusive_tax(False) expense.set_is_billable(True) expense.set_reference_number('2') expense.set_description('') expense.set_customer_id(customer_id) expense.set_vendor_id(vendor_id) expense.set_currency_id('currency_id) expense.set_exchange_rate(20.0) expense.set_project_id('') receipt = '/{file_directory}/download.jpg' print bank_transaction_api.categorize_as_expense(transaction_id,expense) print bank_transaction_api.categorize_as_expense(transaction_id,expense,receipt) # Uncategorize a categorized transaction print bank_transaction_api.uncategorize_a_categorized_transaction(transaction_id)
{ "repo_name": "zoho/books-python-wrappers", "path": "test/BankTransactionTest.py", "copies": "1", "size": "8220", "license": "mit", "hash": -2432907812846444000, "line_mean": 36.7064220183, "line_max": 107, "alpha_frac": 0.7900243309, "autogenerated": false, "ratio": 3.190993788819876, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44810181197198756, "avg_score": null, "num_lines": null }
#$Id$# from books.model.Transaction import Transaction from books.model.TransactionList import TransactionList from books.model.PageContext import PageContext from books.model.Instrumentation import Instrumentation from books.model.SearchCriteria import SearchCriteria class BankTransactionsParser: """This class is used to parse the json response for Bank transactions.""" def get_list(self, resp): """This method parses the given response and returns bank transaction list. Args: resp(dict): Response containing json object for Bank transaction list. Returns: instance: Bank transaction list object. """ bank_transaction_list = TransactionList() for value in resp['banktransactions']: bank_transaction = Transaction() bank_transaction.set_transaction_id(value['transaction_id']) bank_transaction.set_date(value['date']) bank_transaction.set_amount(value['amount']) bank_transaction.set_transaction_type(value['transaction_type']) bank_transaction.set_status(value['status']) bank_transaction.set_source(value['source']) bank_transaction.set_account_id(value['account_id']) bank_transaction.set_customer_id(value['customer_id']) bank_transaction.set_payee(value['payee']) bank_transaction.set_currency_id(value['currency_id']) bank_transaction.set_currency_code(value['currency_code']) bank_transaction.set_debit_or_credit(value['debit_or_credit']) bank_transaction.set_offset_account_name(value['offset_account_name']) bank_transaction.set_reference_number(value['reference_number']) bank_transaction.set_imported_transaction_id(value[\ 'imported_transaction_id']) bank_transaction_list.set_transactions(bank_transaction) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_report_name(page_context['report_name']) page_context_obj.set_applied_filter(page_context['applied_filter']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) bank_transaction_list.set_page_context(page_context_obj) return bank_transaction_list def get_transaction(self, resp): """This method parses the given response and returns Bank Transaction object. Args: resp(dict): Response containing json object for Bank transaction. Returns: instance: Bank transaction object. """ transactions = Transaction() bank_transaction = resp['banktransaction'] transactions.set_transaction_id(bank_transaction['transaction_id']) transactions.set_from_account_id(bank_transaction['from_account_id']) transactions.set_from_account_name(bank_transaction[\ 'from_account_name']) transactions.set_to_account_id(bank_transaction['to_account_id']) transactions.set_to_account_name(bank_transaction['to_account_name']) transactions.set_transaction_type(bank_transaction['transaction_type']) transactions.set_currency_id(bank_transaction['transaction_type']) transactions.set_currency_code(bank_transaction['currency_code']) transactions.set_amount(bank_transaction['amount']) transactions.set_exchange_rate(bank_transaction['exchange_rate']) transactions.set_date(bank_transaction['date']) transactions.set_reference_number(bank_transaction['reference_number']) transactions.set_description(bank_transaction['description']) transactions.set_imported_transaction(bank_transaction[\ 'imported_transactions']) return transactions def get_message(self, resp): """This method parses the given response and returns message. Args: resp(dict): Response containing json object for message. Returns: str: Success message('The transaction hasbeen deleted.'). """ return resp['message'] def get_matching_transaction(self, resp): """This method parses the given response and returns matching transactions list. Args: resp(dict): Response containing json object for matching transactions. Returns: instance: Transaction list object. """ transaction_list = TransactionList() for value in resp['matching_transactions']: transaction = Transaction() transaction.set_transaction_id(value['transaction_id']) transaction.set_date(value['date']) transaction.set_date_formatted(value['date_formatted']) transaction.set_transaction_type(value['transaction_type']) transaction.set_transaction_type_formatted(value[\ 'transaction_type_formatted']) transaction.set_reference_number(value['reference_number']) transaction.set_amount(value['amount']) transaction.set_amount_formatted(value['amount_formatted']) transaction.set_debit_or_credit(value['debit_or_credit']) transaction_list.set_transactions(transaction) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) page_context_obj.set_sort_column(page_context['sort_column']) page_context_obj.set_sort_order(page_context['sort_order']) for value in page_context['search_criteria']: criteria = SearchCriteria() criteria.set_column_name(value['column_name']) criteria.set_search_text(value['search_text']) criteria.set_comparator(value['comparator']) page_context_obj.set_search_criteria(criteria) transaction_list.set_page_context(page_context_obj) '''instrumentation_obj = Instrumentation() instrumentation = resp['instrumentation'] instrumentation_obj.set_query_execution_time(instrumentation[\ 'query_execution_time']) instrumentation_obj.set_request_handling_time(instrumentation[\ 'request_handling_time']) instrumentation_obj.set_response_write_time(instrumentation[\ 'response_write_time']) instrumentation_obj.set_page_context_write_time(instrumentation[\ 'page_context_write_time']) transaction_list.set_instrumentation(instrumentation_obj)''' return transaction_list def get_associated_transaction(self, resp): """This method parses the given response and returns associated transactions list. Args: resp(dict): Response containing json object for associated transactions. Returns: instance: Transaction object. """ transaction = resp['transaction'] transaction_obj = Transaction() transaction_obj.set_imported_transaction_id(transaction[\ 'imported_transaction_id']) transaction_obj.set_date(transaction['date']) transaction_obj.set_amount(transaction['amount']) transaction_obj.set_payee(transaction['payee']) transaction_obj.set_reference_number(transaction['reference_number']) transaction_obj.set_description(transaction['description']) transaction_obj.set_status(transaction['status']) transaction_obj.set_status_formatted(transaction['status_formatted']) for value in transaction['associated_transactions']: transaction = Transaction() transaction.set_transaction_id(value['transaction_id']) transaction.set_date(value['date']) transaction.set_debit_or_credit(value['debit_or_credit']) transaction.set_transaction_type(value['transaction_type']) transaction.set_amount(value['amount']) transaction.set_customer_id(value['customer_id']) transaction.set_customer_name(value['customer_name']) transaction_obj.set_associated_transaction(transaction) page_context_obj = PageContext() page_context = resp['page_context'] page_context_obj.set_page(page_context['page']) page_context_obj.set_per_page(page_context['per_page']) page_context_obj.set_has_more_page(page_context['has_more_page']) '''instrumentation_obj = Instrumentation() instrumentation = resp['instrumentation'] instrumentation_obj.set_query_execution_time(instrumentation[\ 'query_execution_time']) instrumentation_obj.set_request_handling_time(instrumentation[\ 'request_handling_time']) instrumentation_obj.set_response_write_time(instrumentation[\ 'response_write_time']) instrumentation_obj.set_page_context_write_time(instrumentation[\ 'page_context_write_time']) transaction_obj.set_instrumentation(instrumentation_obj)''' return transaction_obj
{ "repo_name": "zoho/books-python-wrappers", "path": "books/parser/BankTransactionsParser.py", "copies": "1", "size": "9550", "license": "mit", "hash": 90512634157426720, "line_mean": 45.359223301, "line_max": 82, "alpha_frac": 0.6584293194, "autogenerated": false, "ratio": 4.435671156525778, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5594100475925778, "avg_score": null, "num_lines": null }