text
stringlengths
0
1.05M
meta
dict
from rdkit import Chem from rdkit.Chem import rdPartialCharges import collections def _isCallable(thing): return (hasattr(collections,'Callable') and isinstance(thing,collections.Callable)) or \ hasattr(thing,'__call__') _descList=[] def _setupDescriptors(namespace): global _descList,descList from rdkit.Chem import GraphDescriptors,MolSurf,Lipinski,Fragments,Crippen from rdkit.Chem.EState import EState_VSA mods = [GraphDescriptors,MolSurf,EState_VSA,Lipinski,Crippen,Fragments] otherMods = [Chem] for nm,thing in namespace.items(): if nm[0]!='_' and _isCallable(thing): _descList.append((nm,thing)) others = [] for mod in otherMods: tmp = dir(mod) for name in tmp: if name[0] != '_': thing = getattr(mod,name) if _isCallable(thing): others.append(name) for mod in mods: tmp = dir(mod) for name in tmp: if name[0] != '_' and name[-1] != '_' and name not in others: # filter out python reference implementations: if name[:2]=='py' and name[2:] in tmp: continue thing = getattr(mod,name) if _isCallable(thing): namespace[name]=thing _descList.append((name,thing)) descList=_descList from rdkit.Chem import rdMolDescriptors as _rdMolDescriptors MolWt = lambda *x,**y:_rdMolDescriptors._CalcMolWt(*x,**y) MolWt.version=_rdMolDescriptors._CalcMolWt_version MolWt.__doc__="""The average molecular weight of the molecule >>> MolWt(Chem.MolFromSmiles('CC')) 30.07 >>> MolWt(Chem.MolFromSmiles('[NH4+].[Cl-]')) 53.49... """ HeavyAtomMolWt=lambda x:MolWt(x,True) HeavyAtomMolWt.__doc__="""The average molecular weight of the molecule ignoring hydrogens >>> HeavyAtomMolWt(Chem.MolFromSmiles('CC')) 24.02... >>> HeavyAtomMolWt(Chem.MolFromSmiles('[NH4+].[Cl-]')) 49.46 """ HeavyAtomMolWt.version="1.0.0" ExactMolWt = lambda *x,**y:_rdMolDescriptors.CalcExactMolWt(*x,**y) ExactMolWt.version=_rdMolDescriptors._CalcExactMolWt_version ExactMolWt.__doc__="""The exact molecular weight of the molecule >>> ExactMolWt(Chem.MolFromSmiles('CC')) 30.04... >>> ExactMolWt(Chem.MolFromSmiles('[13CH3]C')) 31.05... """ def NumValenceElectrons(mol): """ The number of valence electrons the molecule has >>> NumValenceElectrons(Chem.MolFromSmiles('CC')) 14.0 >>> NumValenceElectrons(Chem.MolFromSmiles('C(=O)O')) 18.0 >>> NumValenceElectrons(Chem.MolFromSmiles('C(=O)[O-]')) 18.0 >>> NumValenceElectrons(Chem.MolFromSmiles('C(=O)')) 12.0 """ tbl = Chem.GetPeriodicTable() accum = 0.0 for atom in mol.GetAtoms(): accum += tbl.GetNOuterElecs(atom.GetAtomicNum()) accum -= atom.GetFormalCharge() accum += atom.GetTotalNumHs() return accum NumValenceElectrons.version="1.0.0" def NumRadicalElectrons(mol): """ The number of radical electrons the molecule has (says nothing about spin state) >>> NumRadicalElectrons(Chem.MolFromSmiles('CC')) 0.0 >>> NumRadicalElectrons(Chem.MolFromSmiles('C[CH3]')) 0.0 >>> NumRadicalElectrons(Chem.MolFromSmiles('C[CH2]')) 1.0 >>> NumRadicalElectrons(Chem.MolFromSmiles('C[CH]')) 2.0 >>> NumRadicalElectrons(Chem.MolFromSmiles('C[C]')) 3.0 """ accum = 0.0 for atom in mol.GetAtoms(): accum += atom.GetNumRadicalElectrons() return accum NumRadicalElectrons.version="1.0.0" def _ChargeDescriptors(mol,force=False): if not force and hasattr(mol,'_chargeDescriptors'): return mol._chargeDescriptors chgs = rdPartialCharges.ComputeGasteigerCharges(mol) minChg=500. maxChg=-500. for at in mol.GetAtoms(): chg = float(at.GetProp('_GasteigerCharge')) minChg = min(chg,minChg) maxChg = max(chg,maxChg) res = (minChg,maxChg) mol._chargeDescriptors=res return res def MaxPartialCharge(mol,force=False): _,res = _ChargeDescriptors(mol,force) return res MaxPartialCharge.version="1.0.0" def MinPartialCharge(mol,force=False): res,_ = _ChargeDescriptors(mol,force) return res MinPartialCharge.version="1.0.0" def MaxAbsPartialCharge(mol,force=False): v1,v2 = _ChargeDescriptors(mol,force) return max(abs(v1),abs(v2)) MaxAbsPartialCharge.version="1.0.0" def MinAbsPartialCharge(mol,force=False): v1,v2 = _ChargeDescriptors(mol,force) return min(abs(v1),abs(v2)) MinAbsPartialCharge.version="1.0.0" from rdkit.Chem.EState.EState import MaxEStateIndex,MinEStateIndex,MaxAbsEStateIndex,MinAbsEStateIndex _setupDescriptors(locals()) #------------------------------------ # # doctest boilerplate # def _test(): import doctest,sys return doctest.testmod(sys.modules["__main__"],optionflags=doctest.ELLIPSIS) if __name__ == '__main__': import sys failed,tried = _test() sys.exit(failed)
{ "repo_name": "soerendip42/rdkit", "path": "rdkit/Chem/Descriptors.py", "copies": "2", "size": "5043", "license": "bsd-3-clause", "hash": 2475738674977472000, "line_mean": 25.6825396825, "line_max": 102, "alpha_frac": 0.6859012493, "autogenerated": false, "ratio": 2.847543760587239, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45334450098872386, "avg_score": null, "num_lines": null }
""" SMARTS definitions for the publically available MACCS keys and a MACCS fingerprinter I compared the MACCS fingerprints generated here with those from two other packages (not MDL, unfortunately). Of course there are disagreements between the various fingerprints still, but I think these definitions work pretty well. Some notes: 1) most of the differences have to do with aromaticity 2) there's a discrepancy sometimes because the current RDKit definitions do not require multiple matches to be distinct. e.g. the SMILES C(=O)CC(=O) can match the (hypothetical) key O=CC twice in my definition. It's not clear to me what the correct behavior is. 3) Some keys are not fully defined in the MDL documentation 4) Two keys, 125 and 166, have to be done outside of SMARTS. 5) Key 1 (ISOTOPE) isn't defined Rev history: 2006 (gl): Original open-source release May 2011 (gl): Update some definitions based on feedback from Andrew Dalke """ from __future__ import print_function from rdkit import Chem from rdkit.Chem import rdMolDescriptors from rdkit import DataStructs # these are SMARTS patterns corresponding to the MDL MACCS keys smartsPatts={ 1:('?',0), # ISOTOPE #2:('[#104,#105,#106,#107,#106,#109,#110,#111,#112]',0), # atomic num >103 Not complete 2:('[#104]',0), # limit the above def'n since the RDKit only accepts up to #104 3:('[#32,#33,#34,#50,#51,#52,#82,#83,#84]',0), # Group IVa,Va,VIa Rows 4-6 4:('[Ac,Th,Pa,U,Np,Pu,Am,Cm,Bk,Cf,Es,Fm,Md,No,Lr]',0), # actinide 5:('[Sc,Ti,Y,Zr,Hf]',0), # Group IIIB,IVB (Sc...) 6:('[La,Ce,Pr,Nd,Pm,Sm,Eu,Gd,Tb,Dy,Ho,Er,Tm,Yb,Lu]',0), # Lanthanide 7:('[V,Cr,Mn,Nb,Mo,Tc,Ta,W,Re]',0), # Group VB,VIB,VIIB 8:('[!#6;!#1]1~*~*~*~1',0), # QAAA@1 9:('[Fe,Co,Ni,Ru,Rh,Pd,Os,Ir,Pt]',0), # Group VIII (Fe...) 10:('[Be,Mg,Ca,Sr,Ba,Ra]',0), # Group IIa (Alkaline earth) 11:('*1~*~*~*~1',0), # 4M Ring 12:('[Cu,Zn,Ag,Cd,Au,Hg]',0), # Group IB,IIB (Cu..) 13:('[#8]~[#7](~[#6])~[#6]',0), # ON(C)C 14:('[#16]-[#16]',0), # S-S 15:('[#8]~[#6](~[#8])~[#8]',0), # OC(O)O 16:('[!#6;!#1]1~*~*~1',0), # QAA@1 17:('[#6]#[#6]',0), #CTC 18:('[#5,#13,#31,#49,#81]',0), # Group IIIA (B...) 19:('*1~*~*~*~*~*~*~1',0), # 7M Ring 20:('[#14]',0), #Si 21:('[#6]=[#6](~[!#6;!#1])~[!#6;!#1]',0), # C=C(Q)Q 22:('*1~*~*~1',0), # 3M Ring 23:('[#7]~[#6](~[#8])~[#8]',0), # NC(O)O 24:('[#7]-[#8]',0), # N-O 25:('[#7]~[#6](~[#7])~[#7]',0), # NC(N)N 26:('[#6]=;@[#6](@*)@*',0), # C$=C($A)$A 27:('[I]',0), # I 28:('[!#6;!#1]~[CH2]~[!#6;!#1]',0), # QCH2Q 29:('[#15]',0),# P 30:('[#6]~[!#6;!#1](~[#6])(~[#6])~*',0), # CQ(C)(C)A 31:('[!#6;!#1]~[F,Cl,Br,I]',0), # QX 32:('[#6]~[#16]~[#7]',0), # CSN 33:('[#7]~[#16]',0), # NS 34:('[CH2]=*',0), # CH2=A 35:('[Li,Na,K,Rb,Cs,Fr]',0), # Group IA (Alkali Metal) 36:('[#16R]',0), # S Heterocycle 37:('[#7]~[#6](~[#8])~[#7]',0), # NC(O)N 38:('[#7]~[#6](~[#6])~[#7]',0), # NC(C)N 39:('[#8]~[#16](~[#8])~[#8]',0), # OS(O)O 40:('[#16]-[#8]',0), # S-O 41:('[#6]#[#7]',0), # CTN 42:('F',0), # F 43:('[!#6;!#1;!H0]~*~[!#6;!#1;!H0]',0), # QHAQH 44:('[!#1;!#6;!#7;!#8;!#9;!#14;!#15;!#16;!#17;!#35;!#53]',0), # OTHER 45:('[#6]=[#6]~[#7]',0), # C=CN 46:('Br',0), # BR 47:('[#16]~*~[#7]',0), # SAN 48:('[#8]~[!#6;!#1](~[#8])(~[#8])',0), # OQ(O)O 49:('[!+0]',0), # CHARGE 50:('[#6]=[#6](~[#6])~[#6]',0), # C=C(C)C 51:('[#6]~[#16]~[#8]',0), # CSO 52:('[#7]~[#7]',0), # NN 53:('[!#6;!#1;!H0]~*~*~*~[!#6;!#1;!H0]',0), # QHAAAQH 54:('[!#6;!#1;!H0]~*~*~[!#6;!#1;!H0]',0), # QHAAQH 55:('[#8]~[#16]~[#8]',0), #OSO 56:('[#8]~[#7](~[#8])~[#6]',0), # ON(O)C 57:('[#8R]',0), # O Heterocycle 58:('[!#6;!#1]~[#16]~[!#6;!#1]',0), # QSQ 59:('[#16]!:*:*',0), # Snot%A%A 60:('[#16]=[#8]',0), # S=O 61:('*~[#16](~*)~*',0), # AS(A)A 62:('*@*!@*@*',0), # A$!A$A 63:('[#7]=[#8]',0), # N=O 64:('*@*!@[#16]',0), # A$A!S 65:('c:n',0), # C%N 66:('[#6]~[#6](~[#6])(~[#6])~*',0), # CC(C)(C)A 67:('[!#6;!#1]~[#16]',0), # QS 68:('[!#6;!#1;!H0]~[!#6;!#1;!H0]',0), # QHQH (&...) SPEC Incomplete 69:('[!#6;!#1]~[!#6;!#1;!H0]',0), # QQH 70:('[!#6;!#1]~[#7]~[!#6;!#1]',0), # QNQ 71:('[#7]~[#8]',0), # NO 72:('[#8]~*~*~[#8]',0), # OAAO 73:('[#16]=*',0), # S=A 74:('[CH3]~*~[CH3]',0), # CH3ACH3 75:('*!@[#7]@*',0), # A!N$A 76:('[#6]=[#6](~*)~*',0), # C=C(A)A 77:('[#7]~*~[#7]',0), # NAN 78:('[#6]=[#7]',0), # C=N 79:('[#7]~*~*~[#7]',0), # NAAN 80:('[#7]~*~*~*~[#7]',0), # NAAAN 81:('[#16]~*(~*)~*',0), # SA(A)A 82:('*~[CH2]~[!#6;!#1;!H0]',0), # ACH2QH 83:('[!#6;!#1]1~*~*~*~*~1',0), # QAAAA@1 84:('[NH2]',0), #NH2 85:('[#6]~[#7](~[#6])~[#6]',0), # CN(C)C 86:('[C;H2,H3][!#6;!#1][C;H2,H3]',0), # CH2QCH2 87:('[F,Cl,Br,I]!@*@*',0), # X!A$A 88:('[#16]',0), # S 89:('[#8]~*~*~*~[#8]',0), # OAAAO 90:('[$([!#6;!#1;!H0]~*~*~[CH2]~*),$([!#6;!#1;!H0;R]1@[R]@[R]@[CH2;R]1),$([!#6;!#1;!H0]~[R]1@[R]@[CH2;R]1)]',0), # QHAACH2A 91:('[$([!#6;!#1;!H0]~*~*~*~[CH2]~*),$([!#6;!#1;!H0;R]1@[R]@[R]@[R]@[CH2;R]1),$([!#6;!#1;!H0]~[R]1@[R]@[R]@[CH2;R]1),$([!#6;!#1;!H0]~*~[R]1@[R]@[CH2;R]1)]',0), # QHAAACH2A 92:('[#8]~[#6](~[#7])~[#6]',0), # OC(N)C 93:('[!#6;!#1]~[CH3]',0), # QCH3 94:('[!#6;!#1]~[#7]',0), # QN 95:('[#7]~*~*~[#8]',0), # NAAO 96:('*1~*~*~*~*~1',0), # 5 M ring 97:('[#7]~*~*~*~[#8]',0), # NAAAO 98:('[!#6;!#1]1~*~*~*~*~*~1',0), # QAAAAA@1 99:('[#6]=[#6]',0), # C=C 100:('*~[CH2]~[#7]',0), # ACH2N 101:('[$([R]@1@[R]@[R]@[R]@[R]@[R]@[R]@[R]1),$([R]@1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]1),$([R]@1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]1),$([R]@1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]1),$([R]@1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]1),$([R]@1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]1),$([R]@1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]1)]',0), # 8M Ring or larger. This only handles up to ring sizes of 14 102:('[!#6;!#1]~[#8]',0), # QO 103:('Cl',0), # CL 104:('[!#6;!#1;!H0]~*~[CH2]~*',0), # QHACH2A 105:('*@*(@*)@*',0), # A$A($A)$A 106:('[!#6;!#1]~*(~[!#6;!#1])~[!#6;!#1]',0), # QA(Q)Q 107:('[F,Cl,Br,I]~*(~*)~*',0), # XA(A)A 108:('[CH3]~*~*~*~[CH2]~*',0), # CH3AAACH2A 109:('*~[CH2]~[#8]',0), # ACH2O 110:('[#7]~[#6]~[#8]',0), # NCO 111:('[#7]~*~[CH2]~*',0), # NACH2A 112:('*~*(~*)(~*)~*',0), # AA(A)(A)A 113:('[#8]!:*:*',0), # Onot%A%A 114:('[CH3]~[CH2]~*',0), # CH3CH2A 115:('[CH3]~*~[CH2]~*',0), # CH3ACH2A 116:('[$([CH3]~*~*~[CH2]~*),$([CH3]~*1~*~[CH2]1)]',0), # CH3AACH2A 117:('[#7]~*~[#8]',0), # NAO 118:('[$(*~[CH2]~[CH2]~*),$(*1~[CH2]~[CH2]1)]',1), # ACH2CH2A > 1 119:('[#7]=*',0), # N=A 120:('[!#6;R]',1), # Heterocyclic atom > 1 (&...) Spec Incomplete 121:('[#7;R]',0), # N Heterocycle 122:('*~[#7](~*)~*',0), # AN(A)A 123:('[#8]~[#6]~[#8]',0), # OCO 124:('[!#6;!#1]~[!#6;!#1]',0), # QQ 125:('?',0), # Aromatic Ring > 1 126:('*!@[#8]!@*',0), # A!O!A 127:('*@*!@[#8]',1), # A$A!O > 1 (&...) Spec Incomplete 128:('[$(*~[CH2]~*~*~*~[CH2]~*),$([R]1@[CH2;R]@[R]@[R]@[R]@[CH2;R]1),$(*~[CH2]~[R]1@[R]@[R]@[CH2;R]1),$(*~[CH2]~*~[R]1@[R]@[CH2;R]1)]',0), # ACH2AAACH2A 129:('[$(*~[CH2]~*~*~[CH2]~*),$([R]1@[CH2]@[R]@[R]@[CH2;R]1),$(*~[CH2]~[R]1@[R]@[CH2;R]1)]',0), # ACH2AACH2A 130:('[!#6;!#1]~[!#6;!#1]',1), # QQ > 1 (&...) Spec Incomplete 131:('[!#6;!#1;!H0]',1), # QH > 1 132:('[#8]~*~[CH2]~*',0), # OACH2A 133:('*@*!@[#7]',0), # A$A!N 134:('[F,Cl,Br,I]',0), # X (HALOGEN) 135:('[#7]!:*:*',0), # Nnot%A%A 136:('[#8]=*',1), # O=A>1 137:('[!C;!c;R]',0), # Heterocycle 138:('[!#6;!#1]~[CH2]~*',1), # QCH2A>1 (&...) Spec Incomplete 139:('[O;!H0]',0), # OH 140:('[#8]',3), # O > 3 (&...) Spec Incomplete 141:('[CH3]',2), # CH3 > 2 (&...) Spec Incomplete 142:('[#7]',1), # N > 1 143:('*@*!@[#8]',0), # A$A!O 144:('*!:*:*!:*',0), # Anot%A%Anot%A 145:('*1~*~*~*~*~*~1',1), # 6M ring > 1 146:('[#8]',2), # O > 2 147:('[$(*~[CH2]~[CH2]~*),$([R]1@[CH2;R]@[CH2;R]1)]',0), # ACH2CH2A 148:('*~[!#6;!#1](~*)~*',0), # AQ(A)A 149:('[C;H3,H4]',1), # CH3 > 1 150:('*!@*@*!@*',0), # A!A$A!A 151:('[#7;!H0]',0), # NH 152:('[#8]~[#6](~[#6])~[#6]',0), # OC(C)C 153:('[!#6;!#1]~[CH2]~*',0), # QCH2A 154:('[#6]=[#8]',0), # C=O 155:('*!@[CH2]!@*',0), # A!CH2!A 156:('[#7]~*(~*)~*',0), # NA(A)A 157:('[#6]-[#8]',0), # C-O 158:('[#6]-[#7]',0), # C-N 159:('[#8]',1), # O>1 160:('[C;H3,H4]',0), #CH3 161:('[#7]',0), # N 162:('a',0), # Aromatic 163:('*1~*~*~*~*~*~1',0), # 6M Ring 164:('[#8]',0), # O 165:('[R]',0), # Ring 166:('?',0), # Fragments FIX: this can't be done in SMARTS } maccsKeys = None def _InitKeys(keyList,keyDict): """ *Internal Use Only* generates SMARTS patterns for the keys, run once """ assert len(keyList) == len(keyDict.keys()),'length mismatch' for key in keyDict.keys(): patt,count = keyDict[key] if patt != '?': try: sma = Chem.MolFromSmarts(patt) except: sma = None if not sma: print('SMARTS parser error for key #%d: %s'%(key,patt)) else: keyList[key-1] = sma,count def _pyGenMACCSKeys(mol,**kwargs): """ generates the MACCS fingerprint for a molecules **Arguments** - mol: the molecule to be fingerprinted - any extra keyword arguments are ignored **Returns** a _DataStructs.SparseBitVect_ containing the fingerprint. >>> m = Chem.MolFromSmiles('CNO') >>> bv = GenMACCSKeys(m) >>> tuple(bv.GetOnBits()) (24, 68, 69, 71, 93, 94, 102, 124, 131, 139, 151, 158, 160, 161, 164) >>> bv = GenMACCSKeys(Chem.MolFromSmiles('CCC')) >>> tuple(bv.GetOnBits()) (74, 114, 149, 155, 160) """ global maccsKeys if maccsKeys is None: maccsKeys = [(None,0)]*len(smartsPatts.keys()) _InitKeys(maccsKeys,smartsPatts) ctor=kwargs.get('ctor',DataStructs.SparseBitVect) res = ctor(len(maccsKeys)+1) for i,(patt,count) in enumerate(maccsKeys): if patt is not None: if count==0: res[i+1] = mol.HasSubstructMatch(patt) else: matches = mol.GetSubstructMatches(patt) if len(matches) > count: res[i+1] = 1 elif (i+1)==125: # special case: num aromatic rings > 1 ri = mol.GetRingInfo() nArom=0 res[125]=0 for ring in ri.BondRings(): isArom=True for bondIdx in ring: if not mol.GetBondWithIdx(bondIdx).GetIsAromatic(): isArom=False break if isArom: nArom+=1 if nArom>1: res[125]=1 break elif (i+1)==166: res[166]=0 # special case: num frags > 1 if len(Chem.GetMolFrags(mol))>1: res[166]=1 return res GenMACCSKeys = rdMolDescriptors.GetMACCSKeysFingerprint FingerprintMol = rdMolDescriptors.GetMACCSKeysFingerprint #------------------------------------ # # 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": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/MACCSkeys.py", "copies": "3", "size": "11266", "license": "bsd-3-clause", "hash": -340494744810183800, "line_mean": 36.1815181518, "line_max": 426, "alpha_frac": 0.4567725901, "autogenerated": false, "ratio": 1.9264705882352942, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3883243178335294, "avg_score": null, "num_lines": null }
""" functionality for drawing trees on sping canvases """ from rdkit.sping import pid as piddle import math class VisOpts(object): circRad = 10 minCircRad = 4 maxCircRad = 16 circColor = piddle.Color(0.6,0.6,0.9) terminalEmptyColor = piddle.Color(.8,.8,.2) terminalOnColor = piddle.Color(0.8,0.8,0.8) terminalOffColor = piddle.Color(0.2,0.2,0.2) outlineColor = piddle.transparent lineColor = piddle.Color(0,0,0) lineWidth = 2 horizOffset = 10 vertOffset = 50 labelFont = piddle.Font(face='helvetica',size=10) highlightColor = piddle.Color(1.,1.,.4) highlightWidth = 2 visOpts = VisOpts() def CalcTreeNodeSizes(node): """Recursively calculate the total number of nodes under us. results are set in node.totNChildren for this node and everything underneath it. """ children = node.GetChildren() if len(children) > 0: nHere = 0 nBelow=0 for child in children: CalcTreeNodeSizes(child) nHere = nHere + child.totNChildren if child.nLevelsBelow > nBelow: nBelow = child.nLevelsBelow else: nBelow = 0 nHere = 1 node.nExamples = len(node.GetExamples()) node.totNChildren = nHere node.nLevelsBelow = nBelow+1 def _ExampleCounter(node,min,max): if node.GetTerminal(): cnt = node.nExamples if cnt < min: min = cnt if cnt > max: max = cnt else: for child in node.GetChildren(): provMin,provMax = _ExampleCounter(child,min,max) if provMin < min: min = provMin if provMax > max: max = provMax return min,max def _ApplyNodeScales(node,min,max): if node.GetTerminal(): if max!=min: loc = float(node.nExamples - min)/(max-min) else: loc = .5 node._scaleLoc = loc else: for child in node.GetChildren(): _ApplyNodeScales(child,min,max) def SetNodeScales(node): min,max = 1e8,-1e8 min,max = _ExampleCounter(node,min,max) node._scales=min,max _ApplyNodeScales(node,min,max) def DrawTreeNode(node,loc,canvas,nRes=2,scaleLeaves=False,showPurity=False): """Recursively displays the given tree node and all its children on the canvas """ try: nChildren = node.totNChildren except AttributeError: nChildren = None if nChildren is None: CalcTreeNodeSizes(node) if not scaleLeaves or not node.GetTerminal(): rad = visOpts.circRad else: scaleLoc = getattr(node, "_scaleLoc", 0.5) rad = visOpts.minCircRad + node._scaleLoc*(visOpts.maxCircRad-visOpts.minCircRad) x1 = loc[0] - rad y1 = loc[1] - rad x2 = loc[0] + rad y2 = loc[1] + rad if showPurity and node.GetTerminal(): examples = node.GetExamples() nEx = len(examples) if nEx: tgtVal = int(node.GetLabel()) purity = 0.0 for ex in examples: if int(ex[-1])==tgtVal: purity += 1./len(examples) else: purity = 1.0 deg = purity*math.pi xFact = rad*math.sin(deg) yFact = rad*math.cos(deg) pureX = loc[0]+xFact pureY = loc[1]+yFact children = node.GetChildren() # just move down one level childY = loc[1] + visOpts.vertOffset # this is the left-hand side of the leftmost span childX = loc[0] - ((visOpts.horizOffset+visOpts.circRad)*node.totNChildren)/2 for i in range(len(children)): # center on this child's space child = children[i] halfWidth = ((visOpts.horizOffset+visOpts.circRad)*child.totNChildren)/2 childX = childX + halfWidth childLoc = [childX,childY] canvas.drawLine(loc[0],loc[1],childLoc[0],childLoc[1], visOpts.lineColor,visOpts.lineWidth) DrawTreeNode(child,childLoc,canvas,nRes=nRes,scaleLeaves=scaleLeaves, showPurity=showPurity) # and move over to the leftmost point of the next child childX = childX + halfWidth if node.GetTerminal(): lab = node.GetLabel() cFac = float(lab)/float(nRes-1) if hasattr(node,'GetExamples') and node.GetExamples(): theColor = (1.-cFac)*visOpts.terminalOffColor + cFac*visOpts.terminalOnColor outlColor = visOpts.outlineColor else: theColor = (1.-cFac)*visOpts.terminalOffColor + cFac*visOpts.terminalOnColor outlColor = visOpts.terminalEmptyColor canvas.drawEllipse(x1,y1,x2,y2, outlColor,visOpts.lineWidth, theColor) if showPurity: canvas.drawLine(loc[0],loc[1],pureX,pureY,piddle.Color(1,1,1),2) else: theColor = visOpts.circColor canvas.drawEllipse(x1,y1,x2,y2, visOpts.outlineColor,visOpts.lineWidth, theColor) # this does not need to be done every time canvas.defaultFont=visOpts.labelFont labelStr = str(node.GetLabel()) strLoc = (loc[0] - canvas.stringWidth(labelStr)/2, loc[1]+canvas.fontHeight()/4) canvas.drawString(labelStr,strLoc[0],strLoc[1]) node._bBox = (x1,y1,x2,y2) def CalcTreeWidth(tree): try: tree.totNChildren except AttributeError: CalcTreeNodeSizes(tree) totWidth = tree.totNChildren * (visOpts.circRad+visOpts.horizOffset) return totWidth def DrawTree(tree,canvas,nRes=2,scaleLeaves=False,allowShrink=True,showPurity=False): dims = canvas.size loc = (dims[0]/2,visOpts.vertOffset) if scaleLeaves: #try: # l = tree._scales #except AttributeError: # l = None #if l is None: SetNodeScales(tree) if allowShrink: treeWid = CalcTreeWidth(tree) while treeWid > dims[0]: visOpts.circRad /= 2 visOpts.horizOffset /= 2 treeWid = CalcTreeWidth(tree) DrawTreeNode(tree,loc,canvas,nRes,scaleLeaves=scaleLeaves, showPurity=showPurity) def ResetTree(tree): tree._scales = None tree.totNChildren = None for child in tree.GetChildren(): ResetTree(child) def _simpleTest(canv): from Tree import TreeNode as Node root = Node(None,'r',label='r') c1 = root.AddChild('l1_1',label='l1_1') c2 = root.AddChild('l1_2',isTerminal=1,label=1) c3 = c1.AddChild('l2_1',isTerminal=1,label=0) c4 = c1.AddChild('l2_2',isTerminal=1,label=1) DrawTreeNode(root,(150,visOpts.vertOffset),canv) if __name__ == '__main__': from rdkit.sping.PIL.pidPIL import PILCanvas canv = PILCanvas(size=(300,300),name='test.png') _simpleTest(canv) canv.save()
{ "repo_name": "adalke/rdkit", "path": "rdkit/ML/DecTree/TreeVis.py", "copies": "1", "size": "6400", "license": "bsd-3-clause", "hash": -1397623682040078600, "line_mean": 27.5714285714, "line_max": 85, "alpha_frac": 0.65921875, "autogenerated": false, "ratio": 3.063666826232647, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9018011882622234, "avg_score": 0.04097473872208241, "num_lines": 224 }
""" functionality for drawing trees on sping canvases """ from rdkit.sping import pid as piddle import math class VisOpts(object): circRad = 10 minCircRad = 4 maxCircRad = 16 circColor = piddle.Color(0.6, 0.6, 0.9) terminalEmptyColor = piddle.Color(.8, .8, .2) terminalOnColor = piddle.Color(0.8, 0.8, 0.8) terminalOffColor = piddle.Color(0.2, 0.2, 0.2) outlineColor = piddle.transparent lineColor = piddle.Color(0, 0, 0) lineWidth = 2 horizOffset = 10 vertOffset = 50 labelFont = piddle.Font(face='helvetica', size=10) highlightColor = piddle.Color(1., 1., .4) highlightWidth = 2 visOpts = VisOpts() def CalcTreeNodeSizes(node): """Recursively calculate the total number of nodes under us. results are set in node.totNChildren for this node and everything underneath it. """ children = node.GetChildren() if len(children) > 0: nHere = 0 nBelow = 0 for child in children: CalcTreeNodeSizes(child) nHere = nHere + child.totNChildren if child.nLevelsBelow > nBelow: nBelow = child.nLevelsBelow else: nBelow = 0 nHere = 1 node.nExamples = len(node.GetExamples()) node.totNChildren = nHere node.nLevelsBelow = nBelow + 1 def _ExampleCounter(node, min, max): if node.GetTerminal(): cnt = node.nExamples if cnt < min: min = cnt if cnt > max: max = cnt else: for child in node.GetChildren(): provMin, provMax = _ExampleCounter(child, min, max) if provMin < min: min = provMin if provMax > max: max = provMax return min, max def _ApplyNodeScales(node, min, max): if node.GetTerminal(): if max != min: loc = float(node.nExamples - min) / (max - min) else: loc = .5 node._scaleLoc = loc else: for child in node.GetChildren(): _ApplyNodeScales(child, min, max) def SetNodeScales(node): min, max = 1e8, -1e8 min, max = _ExampleCounter(node, min, max) node._scales = min, max _ApplyNodeScales(node, min, max) def DrawTreeNode(node, loc, canvas, nRes=2, scaleLeaves=False, showPurity=False): """Recursively displays the given tree node and all its children on the canvas """ try: nChildren = node.totNChildren except AttributeError: nChildren = None if nChildren is None: CalcTreeNodeSizes(node) if not scaleLeaves or not node.GetTerminal(): rad = visOpts.circRad else: scaleLoc = getattr(node, "_scaleLoc", 0.5) rad = visOpts.minCircRad + node._scaleLoc * (visOpts.maxCircRad - visOpts.minCircRad) x1 = loc[0] - rad y1 = loc[1] - rad x2 = loc[0] + rad y2 = loc[1] + rad if showPurity and node.GetTerminal(): examples = node.GetExamples() nEx = len(examples) if nEx: tgtVal = int(node.GetLabel()) purity = 0.0 for ex in examples: if int(ex[-1]) == tgtVal: purity += 1. / len(examples) else: purity = 1.0 deg = purity * math.pi xFact = rad * math.sin(deg) yFact = rad * math.cos(deg) pureX = loc[0] + xFact pureY = loc[1] + yFact children = node.GetChildren() # just move down one level childY = loc[1] + visOpts.vertOffset # this is the left-hand side of the leftmost span childX = loc[0] - ((visOpts.horizOffset + visOpts.circRad) * node.totNChildren) / 2 for i in range(len(children)): # center on this child's space child = children[i] halfWidth = ((visOpts.horizOffset + visOpts.circRad) * child.totNChildren) / 2 childX = childX + halfWidth childLoc = [childX, childY] canvas.drawLine(loc[0], loc[1], childLoc[0], childLoc[1], visOpts.lineColor, visOpts.lineWidth) DrawTreeNode(child, childLoc, canvas, nRes=nRes, scaleLeaves=scaleLeaves, showPurity=showPurity) # and move over to the leftmost point of the next child childX = childX + halfWidth if node.GetTerminal(): lab = node.GetLabel() cFac = float(lab) / float(nRes - 1) if hasattr(node, 'GetExamples') and node.GetExamples(): theColor = (1. - cFac) * visOpts.terminalOffColor + cFac * visOpts.terminalOnColor outlColor = visOpts.outlineColor else: theColor = (1. - cFac) * visOpts.terminalOffColor + cFac * visOpts.terminalOnColor outlColor = visOpts.terminalEmptyColor canvas.drawEllipse(x1, y1, x2, y2, outlColor, visOpts.lineWidth, theColor) if showPurity: canvas.drawLine(loc[0], loc[1], pureX, pureY, piddle.Color(1, 1, 1), 2) else: theColor = visOpts.circColor canvas.drawEllipse(x1, y1, x2, y2, visOpts.outlineColor, visOpts.lineWidth, theColor) # this does not need to be done every time canvas.defaultFont = visOpts.labelFont labelStr = str(node.GetLabel()) strLoc = (loc[0] - canvas.stringWidth(labelStr) / 2, loc[1] + canvas.fontHeight() / 4) canvas.drawString(labelStr, strLoc[0], strLoc[1]) node._bBox = (x1, y1, x2, y2) def CalcTreeWidth(tree): try: tree.totNChildren except AttributeError: CalcTreeNodeSizes(tree) totWidth = tree.totNChildren * (visOpts.circRad + visOpts.horizOffset) return totWidth def DrawTree(tree, canvas, nRes=2, scaleLeaves=False, allowShrink=True, showPurity=False): dims = canvas.size loc = (dims[0] / 2, visOpts.vertOffset) if scaleLeaves: #try: # l = tree._scales #except AttributeError: # l = None #if l is None: SetNodeScales(tree) if allowShrink: treeWid = CalcTreeWidth(tree) while treeWid > dims[0]: visOpts.circRad /= 2 visOpts.horizOffset /= 2 treeWid = CalcTreeWidth(tree) DrawTreeNode(tree, loc, canvas, nRes, scaleLeaves=scaleLeaves, showPurity=showPurity) def ResetTree(tree): tree._scales = None tree.totNChildren = None for child in tree.GetChildren(): ResetTree(child) def _simpleTest(canv): from Tree import TreeNode as Node root = Node(None, 'r', label='r') c1 = root.AddChild('l1_1', label='l1_1') c2 = root.AddChild('l1_2', isTerminal=1, label=1) c3 = c1.AddChild('l2_1', isTerminal=1, label=0) c4 = c1.AddChild('l2_2', isTerminal=1, label=1) DrawTreeNode(root, (150, visOpts.vertOffset), canv) if __name__ == '__main__': from rdkit.sping.PIL.pidPIL import PILCanvas canv = PILCanvas(size=(300, 300), name='test.png') _simpleTest(canv) canv.save()
{ "repo_name": "jandom/rdkit", "path": "rdkit/ML/DecTree/TreeVis.py", "copies": "1", "size": "6387", "license": "bsd-3-clause", "hash": -8702271723224396000, "line_mean": 27.0131578947, "line_max": 100, "alpha_frac": 0.6605605135, "autogenerated": false, "ratio": 3.037089871611983, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4197650385111983, "avg_score": null, "num_lines": null }
""" functionality for drawing trees on sping canvases """ import math from rdkit.sping import pid as piddle class VisOpts(object): circRad = 10 minCircRad = 4 maxCircRad = 16 circColor = piddle.Color(0.6, 0.6, 0.9) terminalEmptyColor = piddle.Color(.8, .8, .2) terminalOnColor = piddle.Color(0.8, 0.8, 0.8) terminalOffColor = piddle.Color(0.2, 0.2, 0.2) outlineColor = piddle.transparent lineColor = piddle.Color(0, 0, 0) lineWidth = 2 horizOffset = 10 vertOffset = 50 labelFont = piddle.Font(face='helvetica', size=10) highlightColor = piddle.Color(1., 1., .4) highlightWidth = 2 visOpts = VisOpts() def CalcTreeNodeSizes(node): """Recursively calculate the total number of nodes under us. results are set in node.totNChildren for this node and everything underneath it. """ children = node.GetChildren() if len(children) > 0: nHere = 0 nBelow = 0 for child in children: CalcTreeNodeSizes(child) nHere = nHere + child.totNChildren if child.nLevelsBelow > nBelow: nBelow = child.nLevelsBelow else: nBelow = 0 nHere = 1 node.nExamples = len(node.GetExamples()) node.totNChildren = nHere node.nLevelsBelow = nBelow + 1 def _ExampleCounter(node, min, max): if node.GetTerminal(): cnt = node.nExamples if cnt < min: min = cnt if cnt > max: max = cnt else: for child in node.GetChildren(): provMin, provMax = _ExampleCounter(child, min, max) if provMin < min: min = provMin if provMax > max: max = provMax return min, max def _ApplyNodeScales(node, min, max): if node.GetTerminal(): if max != min: loc = float(node.nExamples - min) / (max - min) else: loc = .5 node._scaleLoc = loc else: for child in node.GetChildren(): _ApplyNodeScales(child, min, max) def SetNodeScales(node): min, max = 1e8, -1e8 min, max = _ExampleCounter(node, min, max) node._scales = min, max _ApplyNodeScales(node, min, max) def DrawTreeNode(node, loc, canvas, nRes=2, scaleLeaves=False, showPurity=False): """Recursively displays the given tree node and all its children on the canvas """ try: nChildren = node.totNChildren except AttributeError: nChildren = None if nChildren is None: CalcTreeNodeSizes(node) if not scaleLeaves or not node.GetTerminal(): rad = visOpts.circRad else: scaleLoc = getattr(node, "_scaleLoc", 0.5) rad = visOpts.minCircRad + node._scaleLoc * (visOpts.maxCircRad - visOpts.minCircRad) x1 = loc[0] - rad y1 = loc[1] - rad x2 = loc[0] + rad y2 = loc[1] + rad if showPurity and node.GetTerminal(): examples = node.GetExamples() nEx = len(examples) if nEx: tgtVal = int(node.GetLabel()) purity = 0.0 for ex in examples: if int(ex[-1]) == tgtVal: purity += 1. / len(examples) else: purity = 1.0 deg = purity * math.pi xFact = rad * math.sin(deg) yFact = rad * math.cos(deg) pureX = loc[0] + xFact pureY = loc[1] + yFact children = node.GetChildren() # just move down one level childY = loc[1] + visOpts.vertOffset # this is the left-hand side of the leftmost span childX = loc[0] - ((visOpts.horizOffset + visOpts.circRad) * node.totNChildren) / 2 for i in range(len(children)): # center on this child's space child = children[i] halfWidth = ((visOpts.horizOffset + visOpts.circRad) * child.totNChildren) / 2 childX = childX + halfWidth childLoc = [childX, childY] canvas.drawLine(loc[0], loc[1], childLoc[0], childLoc[1], visOpts.lineColor, visOpts.lineWidth) DrawTreeNode(child, childLoc, canvas, nRes=nRes, scaleLeaves=scaleLeaves, showPurity=showPurity) # and move over to the leftmost point of the next child childX = childX + halfWidth if node.GetTerminal(): lab = node.GetLabel() cFac = float(lab) / float(nRes - 1) if hasattr(node, 'GetExamples') and node.GetExamples(): theColor = (1. - cFac) * visOpts.terminalOffColor + cFac * visOpts.terminalOnColor outlColor = visOpts.outlineColor else: theColor = (1. - cFac) * visOpts.terminalOffColor + cFac * visOpts.terminalOnColor outlColor = visOpts.terminalEmptyColor canvas.drawEllipse(x1, y1, x2, y2, outlColor, visOpts.lineWidth, theColor) if showPurity: canvas.drawLine(loc[0], loc[1], pureX, pureY, piddle.Color(1, 1, 1), 2) else: theColor = visOpts.circColor canvas.drawEllipse(x1, y1, x2, y2, visOpts.outlineColor, visOpts.lineWidth, theColor) # this does not need to be done every time canvas.defaultFont = visOpts.labelFont labelStr = str(node.GetLabel()) strLoc = (loc[0] - canvas.stringWidth(labelStr) / 2, loc[1] + canvas.fontHeight() / 4) canvas.drawString(labelStr, strLoc[0], strLoc[1]) node._bBox = (x1, y1, x2, y2) def CalcTreeWidth(tree): try: tree.totNChildren except AttributeError: CalcTreeNodeSizes(tree) totWidth = tree.totNChildren * (visOpts.circRad + visOpts.horizOffset) return totWidth def DrawTree(tree, canvas, nRes=2, scaleLeaves=False, allowShrink=True, showPurity=False): dims = canvas.size loc = (dims[0] / 2, visOpts.vertOffset) if scaleLeaves: # try: # l = tree._scales # except AttributeError: # l = None # if l is None: SetNodeScales(tree) if allowShrink: treeWid = CalcTreeWidth(tree) while treeWid > dims[0]: visOpts.circRad /= 2 visOpts.horizOffset /= 2 treeWid = CalcTreeWidth(tree) DrawTreeNode(tree, loc, canvas, nRes, scaleLeaves=scaleLeaves, showPurity=showPurity) def ResetTree(tree): tree._scales = None tree.totNChildren = None for child in tree.GetChildren(): ResetTree(child) def _simpleTest(canv): from .Tree import TreeNode as Node root = Node(None, 'r', label='r') c1 = root.AddChild('l1_1', label='l1_1') c2 = root.AddChild('l1_2', isTerminal=1, label=1) c3 = c1.AddChild('l2_1', isTerminal=1, label=0) c4 = c1.AddChild('l2_2', isTerminal=1, label=1) DrawTreeNode(root, (150, visOpts.vertOffset), canv) if __name__ == '__main__': from rdkit.sping.PIL.pidPIL import PILCanvas canv = PILCanvas(size=(300, 300), name='test.png') _simpleTest(canv) canv.save()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/DecTree/TreeVis.py", "copies": "11", "size": "6394", "license": "bsd-3-clause", "hash": 5713088176838420000, "line_mean": 26.9213973799, "line_max": 100, "alpha_frac": 0.6598373475, "autogenerated": false, "ratio": 3.0375296912114016, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.01823990198679555, "num_lines": 229 }
""" primitive license handler License file format: (lines beginning with # are ignored) Expiration_Date: <expiration date of license> Verification: <verification code> Date format: day-month-year The verification code is used to ensure that the date has not been tampered with """ import sha,base64,time,exceptions EXPIRED=-1 BADMODULE=0 class LicenseError(exceptions.Exception): pass # this is a base64 encoding of the string "RD License Manager" # it's done this way to provide minimal security (by preventing # a simple run of "strings") _salt='UkQgTGljZW5zZSBNYW5hZ2Vy\n' # # Verification strings are constructed using the SHA # digest of the message formed from: # 1) the results of base64 decoding _salt (defined above) # 2) the text of the Expiration Date # 3) the string representation of the int form of the # time.mktime() date corresponding to the Expiration Date def _Verify(lines): verifier = sha.new(base64.decodestring(_salt)) inL = lines[0] if inL == '': raise LicenseError,'EOF hit parsing license file' if inL.find('Expiration_Date:')==-1: raise LicenseError,'bad license file format' dText = inL.split(':')[-1].strip() verifier.update(dText) try: dateComponents = map(int,dText.split('-')) except: dateComponents = [] if len(dateComponents) != 3: raise LicenseError,'bad date format in license file' day,month,year = dateComponents pos = 1 for line in lines: if line.find('Modules:')!=-1: break if line.find('Modules:') != -1: modules = line.split(':')[-1].strip().upper().split(',') #modules = ','.join([x.strip() for x in modules.split(',')]) else: modules = '' pos = 1 inL = lines[pos] while pos < len(lines) and inL.find('Verification:')==-1: pos += 1 inL = lines[pos] if inL == '': raise LicenseError,'EOF hit parsing license file' if inL.find('Verification:')==-1: raise LicenseError,'bad license file format' vText = inL.split(':')[-1].strip() expDate = int(time.mktime((year,month,day, 0,0,0, 0,0,0))) verifier.update(str(expDate)) verifier.update(','.join(modules)) if verifier.hexdigest() != vText: raise LicenseError,'verification of license file failed' # ok, the license file has not been tampered with... proceed return expDate,modules def _CheckDate(expDate): year,month,day,h,m,s,w,d,dst = time.gmtime() newD = int(time.mktime((year,month,day, 0,0,0, 0,0,0))) if expDate > newD: return 1 else: return 0 def CheckLicenseFile(filename): try: inF = open(filename,'r') except IOError: raise LicenseError,'License file %s could not be opened'%(filename) lines = [] for line in inF.readlines(): if len(line) and line[0] != '#': lines.append(line.strip()) expDate,modules = _Verify(lines) if not _CheckDate(expDate): return EXPIRED def CheckLicenseString(text,checkModule=None): lines = text.split('\n') expDate,modules = _Verify(lines) if not _CheckDate(expDate): return EXPIRED if checkModule: if checkModule.upper() not in modules: return BADMODULE return 1 if __name__ == '__main__': import sys if len(sys.argv)>1: for nm in sys.argv[1:]: print nm,CheckLicenseFile(nm),CheckLicenseString(open(nm,'r').read())
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/utils/Licensing.py", "copies": "2", "size": "3541", "license": "bsd-3-clause", "hash": -3565820362353905000, "line_mean": 25.4253731343, "line_max": 75, "alpha_frac": 0.6447331262, "autogenerated": false, "ratio": 3.48180924287119, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.512654236907119, "avg_score": null, "num_lines": null }
""" Basic EState definitions """ from __future__ import print_function import numpy from rdkit import Chem def GetPrincipleQuantumNumber(atNum): if atNum<=2: return 1 elif atNum <= 10: return 2 elif atNum <= 18: return 3 elif atNum <= 36: return 4 elif atNum <= 54: return 5 elif atNum <= 86: return 6 else: return 7 def EStateIndices(mol,force=1): """ returns a tuple of EState indices for the molecule Reference: Hall, Mohney and Kier. JCICS _31_ 76-81 (1991) """ if not force and hasattr(mol,'_eStateIndices'): return mol._eStateIndices tbl = Chem.GetPeriodicTable() nAtoms = mol.GetNumAtoms() Is = numpy.zeros(nAtoms,numpy.float) for i in range(nAtoms): at = mol.GetAtomWithIdx(i) atNum = at.GetAtomicNum() d = at.GetDegree() if d>0: h = at.GetTotalNumHs() dv = tbl.GetNOuterElecs(atNum)-h N = GetPrincipleQuantumNumber(atNum) Is[i] = (4./(N*N) * dv + 1)/d dists = Chem.GetDistanceMatrix(mol,useBO=0,useAtomWts=0) dists += 1 accum = numpy.zeros(nAtoms,numpy.float) for i in range(nAtoms): for j in range(i+1,nAtoms): p = dists[i,j] if p < 1e6: tmp = (Is[i]-Is[j])/(p*p) accum[i] += tmp accum[j] -= tmp res = accum+Is mol._eStateIndices=res return res EStateIndices.version='1.0.0' def MaxEStateIndex(mol,force=1): return max(EStateIndices(mol,force)); MaxEStateIndex.version="1.0.0" def MinEStateIndex(mol,force=1): return min(EStateIndices(mol,force)); MinEStateIndex.version="1.0.0" def MaxAbsEStateIndex(mol,force=1): return max([abs(x) for x in EStateIndices(mol,force)]); MaxAbsEStateIndex.version="1.0.0" def MinAbsEStateIndex(mol,force=1): return min([abs(x) for x in EStateIndices(mol,force)]); MinAbsEStateIndex.version="1.0.0" if __name__ =='__main__': smis = ['CCCC','CCCCC','CCCCCC','CC(N)C(=O)O','CC(N)C(=O)[O-].[Na+]'] for smi in smis: m = Chem.MolFromSmiles(smi) print(smi) inds = EStateIndices(m) print('\t',inds)
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/EState/EState.py", "copies": "4", "size": "2309", "license": "bsd-3-clause", "hash": 306969762627453250, "line_mean": 25.2386363636, "line_max": 71, "alpha_frac": 0.6569943699, "autogenerated": false, "ratio": 2.7132784958871916, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5370272865787191, "avg_score": null, "num_lines": null }
""" Basic EState definitions """ from __future__ import print_function import numpy from rdkit import Chem def GetPrincipleQuantumNumber(atNum): """ Get principal quantum number for atom number """ if atNum <= 2: return 1 elif atNum <= 10: return 2 elif atNum <= 18: return 3 elif atNum <= 36: return 4 elif atNum <= 54: return 5 elif atNum <= 86: return 6 else: return 7 def EStateIndices(mol, force=True): """ returns a tuple of EState indices for the molecule Reference: Hall, Mohney and Kier. JCICS _31_ 76-81 (1991) """ if not force and hasattr(mol, '_eStateIndices'): return mol._eStateIndices tbl = Chem.GetPeriodicTable() nAtoms = mol.GetNumAtoms() Is = numpy.zeros(nAtoms, numpy.float) for i in range(nAtoms): at = mol.GetAtomWithIdx(i) atNum = at.GetAtomicNum() d = at.GetDegree() if d > 0: h = at.GetTotalNumHs() dv = tbl.GetNOuterElecs(atNum) - h N = GetPrincipleQuantumNumber(atNum) Is[i] = (4. / (N * N) * dv + 1) / d dists = Chem.GetDistanceMatrix(mol, useBO=0, useAtomWts=0) dists += 1 accum = numpy.zeros(nAtoms, numpy.float) for i in range(nAtoms): for j in range(i + 1, nAtoms): p = dists[i, j] if p < 1e6: tmp = (Is[i] - Is[j]) / (p * p) accum[i] += tmp accum[j] -= tmp res = accum + Is mol._eStateIndices = res return res EStateIndices.version = '1.0.0' def MaxEStateIndex(mol, force=1): return max(EStateIndices(mol, force)) MaxEStateIndex.version = "1.0.0" def MinEStateIndex(mol, force=1): return min(EStateIndices(mol, force)) MinEStateIndex.version = "1.0.0" def MaxAbsEStateIndex(mol, force=1): return max([abs(x) for x in EStateIndices(mol, force)]) MaxAbsEStateIndex.version = "1.0.0" def MinAbsEStateIndex(mol, force=1): return min([abs(x) for x in EStateIndices(mol, force)]) MinAbsEStateIndex.version = "1.0.0" def _exampleCode(): """ Example code for calculating E-state indices """ smis = ['CCCC', 'CCCCC', 'CCCCCC', 'CC(N)C(=O)O', 'CC(N)C(=O)[O-].[Na+]'] for smi in smis: m = Chem.MolFromSmiles(smi) print(smi) inds = EStateIndices(m) print('\t', inds) if __name__ == '__main__': # pragma: nocover _exampleCode()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/EState/EState.py", "copies": "5", "size": "2569", "license": "bsd-3-clause", "hash": -3868424661285106000, "line_mean": 21.1465517241, "line_max": 75, "alpha_frac": 0.6360451538, "autogenerated": false, "ratio": 2.804585152838428, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5940630306638428, "avg_score": null, "num_lines": null }
""" Basic EState definitions """ import numpy from rdkit import Chem def GetPrincipleQuantumNumber(atNum): if atNum<=2: return 1 elif atNum <= 10: return 2 elif atNum <= 18: return 3 elif atNum <= 36: return 4 elif atNum <= 54: return 5 elif atNum <= 86: return 6 else: return 7 def EStateIndices(mol,force=1): """ returns a tuple of EState indices for the molecule Reference: Hall, Mohney and Kier. JCICS _31_ 76-81 (1991) """ if not force and hasattr(mol,'_eStateIndices'): return mol._eStateIndices tbl = Chem.GetPeriodicTable() nAtoms = mol.GetNumAtoms() Is = numpy.zeros(nAtoms,numpy.float) for i in range(nAtoms): at = mol.GetAtomWithIdx(i) atNum = at.GetAtomicNum() d = at.GetDegree() if d>0: h = at.GetTotalNumHs() dv = tbl.GetNOuterElecs(atNum)-h N = GetPrincipleQuantumNumber(atNum) Is[i] = (4./(N*N) * dv + 1)/d dists = Chem.GetDistanceMatrix(mol,useBO=0,useAtomWts=0) dists += 1 accum = numpy.zeros(nAtoms,numpy.float) for i in range(nAtoms): for j in range(i+1,nAtoms): p = dists[i,j] if p < 1e6: tmp = (Is[i]-Is[j])/(p*p) accum[i] += tmp accum[j] -= tmp res = accum+Is mol._eStateIndices=res return res EStateIndices.version='1.0.0' if __name__ =='__main__': smis = ['CCCC','CCCCC','CCCCCC','CC(N)C(=O)O','CC(N)C(=O)[O-].[Na+]'] for smi in smis: m = Chem.MolFromSmiles(smi) print smi inds = EStateIndices(m) print '\t',inds
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/EState/EState.py", "copies": "1", "size": "1801", "license": "bsd-3-clause", "hash": -3043713140537822000, "line_mean": 24.3661971831, "line_max": 71, "alpha_frac": 0.6307606885, "autogenerated": false, "ratio": 2.7836166924265844, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3914377380926584, "avg_score": null, "num_lines": null }
""" contains a class to store parameters for and results from Composite building """ from rdkit import RDConfig from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbModule def SetDefaults(runDetails): """ initializes a details object with default values **Arguments** - details: (optional) a _CompositeRun.CompositeRun_ object. If this is not provided, the global _runDetails will be used. **Returns** the initialized _CompositeRun_ object. """ runDetails.nRuns = 1 runDetails.nModels = 10 runDetails.outName = '' runDetails.badName = '' runDetails.splitRun = 0 runDetails.splitFrac = 0.7 runDetails.lockRandom = 0 runDetails.randomActivities = 0 runDetails.shuffleActivities = 0 runDetails.replacementSelection = 0 # # Tree Parameters # runDetails.useTrees = 1 runDetails.pruneIt = 0 runDetails.lessGreedy = 0 runDetails.limitDepth = -1 runDetails.recycleVars = 0 runDetails.randomDescriptors = 0 # toggles growing of random forests # # KNN Parameters # runDetails.useKNN = 0 runDetails.knnDistFunc = '' runDetails.knnNeighs = 0 # # SigTree Parameters # runDetails.useSigTrees = 0 runDetails.useCMIM = 0 runDetails.allowCollections = False # # Naive Bayes Classifier Parameters # runDetails.useNaiveBayes = 0 runDetails.mEstimateVal = -1.0 runDetails.useSigBayes = 0 # # # # SVM Parameters # # # runDetails.useSVM = 0 # runDetails.svmKernel = SVM.radialKernel # runDetails.svmType = SVM.cSVCType # runDetails.svmGamma = None # runDetails.svmCost = None # runDetails.svmWeights = None # runDetails.svmDataType = 'float' # runDetails.svmDegree = 3 # runDetails.svmCoeff = 0.0 # runDetails.svmEps = 0.001 # runDetails.svmNu = 0.5 # runDetails.svmCache = 40 # runDetails.svmShrink = 1 # runDetails.svmDataType='float' runDetails.bayesModel = 0 runDetails.dbName = '' runDetails.dbUser = RDConfig.defaultDBUser runDetails.dbPassword = RDConfig.defaultDBPassword runDetails.dbWhat = '*' runDetails.dbWhere = '' runDetails.dbJoin = '' runDetails.qTableName = '' runDetails.qBounds = [] runDetails.qBoundCount = '' runDetails.activityBounds = [] runDetails.activityBoundsVals = '' runDetails.detailedRes = 0 runDetails.noScreen = 0 runDetails.threshold = 0.0 runDetails.filterFrac = 0.0 runDetails.filterVal = 0.0 runDetails.modelFilterVal = 0.0 runDetails.modelFilterFrac = 0.0 runDetails.internalHoldoutFrac = 0.3 runDetails.pickleDataFileName = '' runDetails.startAt = None runDetails.persistTblName = '' runDetails.randomSeed = (23, 42) runDetails.note = '' return runDetails class CompositeRun: """ class to store parameters for and results from Composite building This class has a default set of fields which are added to the database. By default these fields are stored in a tuple, so they are immutable. This is probably what you want. """ fields = (("rundate", "varchar(32)"), ("dbName", "varchar(200)"), ("dbWhat", "varchar(200)"), ("dbWhere", "varchar(200)"), ("dbJoin", "varchar(200)"), ("tableName", "varchar(80)"), ("note", "varchar(120)"), ("shuffled", "smallint"), ("randomized", "smallint"), ("overall_error", "float"), ("holdout_error", "float"), ("overall_fraction_dropped", "float"), ("holdout_fraction_dropped", "float"), ("overall_correct_conf", "float"), ("overall_incorrect_conf", "float"), ("holdout_correct_conf", "float"), ("holdout_incorrect_conf", "float"), ("overall_result_matrix", "varchar(256)"), ("holdout_result_matrix", "varchar(256)"), ("threshold", "float"), ("splitFrac", "float"), ("filterFrac", "float"), ("filterVal", "float"), ("modelFilterVal", "float"), ("modelFilterFrac", "float"), ("nModels", "int"), ("limitDepth", "int"), ("bayesModels", "int"), ("qBoundCount", "varchar(3000)"), ("activityBoundsVals", "varchar(200)"), ("cmd", "varchar(500)"), ("model", DbModule.binaryTypeName), ) def _CreateTable(self, cn, tblName): """ *Internal Use only* """ names = map(lambda x: x.strip().upper(), cn.GetTableNames()) if tblName.upper() not in names: curs = cn.GetCursor() fmt = [] for name, value in self.fields: fmt.append('%s %s' % (name, value)) fmtStr = ','.join(fmt) curs.execute('create table %s (%s)' % (tblName, fmtStr)) cn.Commit() else: heads = [x.upper() for x in cn.GetColumnNames()] curs = cn.GetCursor() for name, value in self.fields: if name.upper() not in heads: curs.execute('alter table %s add %s %s' % (tblName, name, value)) cn.Commit() def Store(self, db='models.gdb', table='results', user='sysdba', password='masterkey'): """ adds the result to a database **Arguments** - db: name of the database to use - table: name of the table to use - user&password: connection information """ cn = DbConnect(db, table, user, password) curs = cn.GetCursor() self._CreateTable(cn, table) cols = [] vals = [] for name, _ in self.fields: try: v = getattr(self, name) except AttributeError: pass else: cols.append('%s' % name) vals.append(v) nToDo = len(vals) qs = ','.join([DbModule.placeHolder] * nToDo) vals = tuple(vals) cmd = 'insert into %s (%s) values (%s)' % (table, ','.join(cols), qs) curs.execute(cmd, vals) cn.Commit() def GetDataSet(self, **kwargs): """ Returns a MLDataSet pulled from a database using our stored values. """ from rdkit.ML.Data import DataUtils data = DataUtils.DBToData(self.dbName, self.tableName, user=self.dbUser, password=self.dbPassword, what=self.dbWhat, where=self.dbWhere, join=self.dbJoin, **kwargs) return data def GetDataSetInfo(self, **kwargs): """ Returns a MLDataSet pulled from a database using our stored values. """ conn = DbConnect(self.dbName, self.tableName) res = conn.GetColumnNamesAndTypes(join=self.dbJoin, what=self.dbWhat, where=self.dbWhere) return res
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/CompositeRun.py", "copies": "11", "size": "6898", "license": "bsd-3-clause", "hash": -724083832772147800, "line_mean": 27.622406639, "line_max": 93, "alpha_frac": 0.6171354016, "autogenerated": false, "ratio": 3.585239085239085, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9702374486839085, "avg_score": null, "num_lines": null }
""" contains a class to store parameters for and results from Composite building """ from rdkit import RDConfig from rdkit.Dbase.DbConnection import DbConnect from rdkit import DataStructs from rdkit.Dbase import DbModule ##from rdkit.ML.SVM import SVMClassificationModel as SVM def SetDefaults(runDetails): """ initializes a details object with default values **Arguments** - details: (optional) a _CompositeRun.CompositeRun_ object. If this is not provided, the global _runDetails will be used. **Returns** the initialized _CompositeRun_ object. """ runDetails.nRuns = 1 runDetails.nModels = 10 runDetails.outName = '' runDetails.badName = '' runDetails.splitRun = 0 runDetails.splitFrac = 0.7 runDetails.lockRandom = 0 runDetails.randomActivities = 0 runDetails.shuffleActivities = 0 runDetails.replacementSelection = 0 # # Tree Parameters # runDetails.useTrees = 1 runDetails.pruneIt = 0 runDetails.lessGreedy = 0 runDetails.limitDepth = -1 runDetails.recycleVars = 0 runDetails.randomDescriptors = 0 # toggles growing of random forests # # KNN Parameters # runDetails.useKNN = 0 runDetails.knnDistFunc = '' runDetails.knnNeighs = 0 # # SigTree Parameters # runDetails.useSigTrees = 0 runDetails.useCMIM = 0 runDetails.allowCollections = False # # Naive Bayes Classifier Parameters # runDetails.useNaiveBayes = 0 runDetails.mEstimateVal = -1.0 runDetails.useSigBayes = 0 ## # ## # SVM Parameters ## # ## runDetails.useSVM = 0 ## runDetails.svmKernel = SVM.radialKernel ## runDetails.svmType = SVM.cSVCType ## runDetails.svmGamma = None ## runDetails.svmCost = None ## runDetails.svmWeights = None ## runDetails.svmDataType = 'float' ## runDetails.svmDegree = 3 ## runDetails.svmCoeff = 0.0 ## runDetails.svmEps = 0.001 ## runDetails.svmNu = 0.5 ## runDetails.svmCache = 40 ## runDetails.svmShrink = 1 ## runDetails.svmDataType='float' runDetails.bayesModel = 0 runDetails.dbName = '' runDetails.dbUser = RDConfig.defaultDBUser runDetails.dbPassword = RDConfig.defaultDBPassword runDetails.dbWhat = '*' runDetails.dbWhere = '' runDetails.dbJoin = '' runDetails.qTableName = '' runDetails.qBounds = [] runDetails.qBoundCount = '' runDetails.activityBounds = [] runDetails.activityBoundsVals = '' runDetails.detailedRes = 0 runDetails.noScreen = 0 runDetails.threshold = 0.0 runDetails.filterFrac = 0.0 runDetails.filterVal = 0.0 runDetails.modelFilterVal = 0.0 runDetails.modelFilterFrac = 0.0 runDetails.internalHoldoutFrac = 0.3 runDetails.pickleDataFileName = '' runDetails.startAt = None runDetails.persistTblName = '' runDetails.randomSeed = (23, 42) runDetails.note = '' return runDetails class CompositeRun: """ class to store parameters for and results from Composite building This class has a default set of fields which are added to the database. By default these fields are stored in a tuple, so they are immutable. This is probably what you want. """ fields = (\ ("rundate","varchar(32)"), ("dbName","varchar(200)"), ("dbWhat","varchar(200)"), ("dbWhere","varchar(200)"), ("dbJoin","varchar(200)"), ("tableName","varchar(80)"), ("note","varchar(120)"), ("shuffled","smallint"), ("randomized","smallint"), ("overall_error","float"), ("holdout_error","float"), ("overall_fraction_dropped","float"), ("holdout_fraction_dropped","float"), ("overall_correct_conf","float"), ("overall_incorrect_conf","float"), ("holdout_correct_conf","float"), ("holdout_incorrect_conf","float"), ("overall_result_matrix","varchar(256)"), ("holdout_result_matrix","varchar(256)"), ("threshold","float"), ("splitFrac","float"), ("filterFrac","float"), ("filterVal","float"), ("modelFilterVal", "float"), ("modelFilterFrac", "float"), ("nModels","int"), ("limitDepth","int"), ("bayesModels","int"), ("qBoundCount","varchar(3000)"), ("activityBoundsVals","varchar(200)"), ("cmd","varchar(500)"), ("model",DbModule.binaryTypeName), ) def _CreateTable(self, cn, tblName): """ *Internal Use only* """ names = map(lambda x: x.strip().upper(), cn.GetTableNames()) if tblName.upper() not in names: curs = cn.GetCursor() fmt = [] for name, value in self.fields: fmt.append('%s %s' % (name, value)) fmtStr = ','.join(fmt) curs.execute('create table %s (%s)' % (tblName, fmtStr)) cn.Commit() else: heads = [x.upper() for x in cn.GetColumnNames()] curs = cn.GetCursor() for name, value in self.fields: if name.upper() not in heads: curs.execute('alter table %s add %s %s' % (tblName, name, value)) cn.Commit() def Store(self, db='models.gdb', table='results', user='sysdba', password='masterkey'): """ adds the result to a database **Arguments** - db: name of the database to use - table: name of the table to use - user&password: connection information """ cn = DbConnect(db, table, user, password) curs = cn.GetCursor() self._CreateTable(cn, table) cols = [] vals = [] for name, typ in self.fields: try: v = getattr(self, name) except AttributeError: pass else: cols.append('%s' % name) vals.append(v) nToDo = len(vals) qs = ','.join([DbModule.placeHolder] * nToDo) vals = tuple(vals) cmd = 'insert into %s (%s) values (%s)' % (table, ','.join(cols), qs) curs.execute(cmd, vals) cn.Commit() def GetDataSet(self, **kwargs): """ Returns a MLDataSet pulled from a database using our stored values. """ from rdkit.ML.Data import DataUtils data = DataUtils.DBToData(self.dbName, self.tableName, user=self.dbUser, password=self.dbPassword, what=self.dbWhat, where=self.dbWhere, join=self.dbJoin, **kwargs) return data def GetDataSetInfo(self, **kwargs): """ Returns a MLDataSet pulled from a database using our stored values. """ from rdkit.Dbase.DbConnection import DbConnect conn = DbConnect(self.dbName, self.tableName) res = conn.GetColumnNamesAndTypes(join=self.dbJoin, what=self.dbWhat, where=self.dbWhere) return res
{ "repo_name": "jandom/rdkit", "path": "rdkit/ML/CompositeRun.py", "copies": "1", "size": "6791", "license": "bsd-3-clause", "hash": -8996916720078619000, "line_mean": 26.4939271255, "line_max": 93, "alpha_frac": 0.6440877632, "autogenerated": false, "ratio": 3.5041279669762644, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46482157301762644, "avg_score": null, "num_lines": null }
""" contains SMARTS definitions and calculators for EState atom types defined in: Hall and Kier JCICS _35_ 1039-1045 (1995) Table 1 """ from rdkit import Chem _rawD = [ ('sLi','[LiD1]-*'), ('ssBe','[BeD2](-*)-*'), ('ssssBe','[BeD4](-*)(-*)(-*)-*'), ('ssBH', '[BD2H](-*)-*'), ('sssB', '[BD3](-*)(-*)-*'), ('ssssB','[BD4](-*)(-*)(-*)-*'), ('sCH3', '[CD1H3]-*'), ('dCH2', '[CD1H2]=*'), ('ssCH2','[CD2H2](-*)-*'), ('tCH', '[CD1H]#*'), ('dsCH', '[CD2H](=*)-*'), ('aaCH', '[C,c;D2H](:*):*'), ('sssCH','[CD3H](-*)(-*)-*'), ('ddC', '[CD2H0](=*)=*'), ('tsC', '[CD2H0](#*)-*'), ('dssC', '[CD3H0](=*)(-*)-*'), ('aasC', '[C,c;D3H0](:*)(:*)-*'), ('aaaC', '[C,c;D3H0](:*)(:*):*'), ('ssssC','[CD4H0](-*)(-*)(-*)-*'), ('sNH3', '[ND1H3]-*'), ('sNH2', '[ND1H2]-*'), ('ssNH2','[ND2H2](-*)-*'), ('dNH', '[ND1H]=*'), ('ssNH', '[ND2H](-*)-*'), ('aaNH', '[N,nD2H](:*):*'), ('tN', '[ND1H0]#*'), ('sssNH','[ND3H](-*)(-*)-*'), ('dsN', '[ND2H0](=*)-*'), ('aaN', '[N,nD2H0](:*):*'), ('sssN', '[ND3H0](-*)(-*)-*'), ('ddsN', '[ND3H0](~[OD1H0])(~[OD1H0])-,:*'), # mod ('aasN', '[N,nD3H0](:*)(:*)-,:*'), # mod ('ssssN','[ND4H0](-*)(-*)(-*)-*'), ('sOH','[OD1H]-*'), ('dO', '[OD1H0]=*'), ('ssO','[OD2H0](-*)-*'), ('aaO','[O,oD2H0](:*):*'), ('sF','[FD1]-*'), ('sSiH3', '[SiD1H3]-*'), ('ssSiH2','[SiD2H2](-*)-*'), ('sssSiH','[SiD3H1](-*)(-*)-*'), ('ssssSi','[SiD4H0](-*)(-*)(-*)-*'), ('sPH2', '[PD1H2]-*'), ('ssPH', '[PD2H1](-*)-*'), ('sssP', '[PD3H0](-*)(-*)-*'), ('dsssP', '[PD4H0](=*)(-*)(-*)-*'), ('sssssP','[PD5H0](-*)(-*)(-*)(-*)-*'), ('sSH', '[SD1H1]-*'), ('dS', '[SD1H0]=*'), ('ssS', '[SD2H0](-*)-*'), ('aaS', '[S,sD2H0](:*):*'), ('dssS', '[SD3H0](=*)(-*)-*'), ('ddssS','[SD4H0](~[OD1H0])(~[OD1H0])(-*)-*'), # mod ('sCl', '[ClD1]-*'), ('sGeH3', '[GeD1H3](-*)'), ('ssGeH2','[GeD2H2](-*)-*'), ('sssGeH','[GeD3H1](-*)(-*)-*'), ('ssssGe','[GeD4H0](-*)(-*)(-*)-*'), ('sAsH2', '[AsD1H2]-*'), ('ssAsH', '[AsD2H1](-*)-*'), ('sssAs', '[AsD3H0](-*)(-*)-*'), ('sssdAs', '[AsD4H0](=*)(-*)(-*)-*'), ('sssssAs','[AsD5H0](-*)(-*)(-*)(-*)-*'), ('sSeH', '[SeD1H1]-*'), ('dSe', '[SeD1H0]=*'), ('ssSe', '[SeD2H0](-*)-*'), ('aaSe', '[SeD2H0](:*):*'), ('dssSe', '[SeD3H0](=*)(-*)-*'), ('ddssSe','[SeD4H0](=*)(=*)(-*)-*'), ('sBr','[BrD1]-*'), ('sSnH3', '[SnD1H3]-*'), ('ssSnH2','[SnD2H2](-*)-*'), ('sssSnH','[SnD3H1](-*)(-*)-*'), ('ssssSn','[SnD4H0](-*)(-*)(-*)-*'), ('sI','[ID1]-*'), ('sPbH3', '[PbD1H3]-*'), ('ssPbH2','[PbD2H2](-*)-*'), ('sssPbH','[PbD3H1](-*)(-*)-*'), ('ssssPb','[PbD4H0](-*)(-*)(-*)-*'), ] esPatterns=None def BuildPatts(rawV=None): """ Internal Use Only """ global esPatterns,_rawD if rawV is None: rawV = _rawD esPatterns = [None]*len(rawV) for i,(name,sma) in enumerate(rawV): try: patt = Chem.MolFromSmarts(sma) except: sys.stderr.write('WARNING: problems with pattern %s (name: %s), skipped.\n'%(sma,name)) else: esPatterns[i] = name,patt def TypeAtoms(mol): """ assigns each atom in a molecule to an EState type **Returns:** list of tuples (atoms can possibly match multiple patterns) with atom types """ if esPatterns is None: BuildPatts() nAtoms = mol.GetNumAtoms() res = [None]*nAtoms for name,patt in esPatterns: matches = mol.GetSubstructMatches(patt,uniquify=0) for match in matches: idx = match[0] if res[idx] is None: res[idx] = [name] elif name not in res[idx]: res[idx].append(name) for i,v in enumerate(res): if v is not None: res[i] = tuple(v) else: res[i] = () return res
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/EState/AtomTypes.py", "copies": "5", "size": "4037", "license": "bsd-3-clause", "hash": -2913885408653060000, "line_mean": 24.0745341615, "line_max": 93, "alpha_frac": 0.4357195938, "autogenerated": false, "ratio": 2.0906266183324704, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9912831813256275, "avg_score": 0.02270287977523917, "num_lines": 161 }
""" contains SMARTS definitions and calculators for EState atom types defined in: Hall and Kier JCICS _35_ 1039-1045 (1995) Table 1 """ from rdkit import Chem _rawD = [ ('sLi', '[LiD1]-*'), ('ssBe', '[BeD2](-*)-*'), ('ssssBe', '[BeD4](-*)(-*)(-*)-*'), ('ssBH', '[BD2H](-*)-*'), ('sssB', '[BD3](-*)(-*)-*'), ('ssssB', '[BD4](-*)(-*)(-*)-*'), ('sCH3', '[CD1H3]-*'), ('dCH2', '[CD1H2]=*'), ('ssCH2', '[CD2H2](-*)-*'), ('tCH', '[CD1H]#*'), ('dsCH', '[CD2H](=*)-*'), ('aaCH', '[C,c;D2H](:*):*'), ('sssCH', '[CD3H](-*)(-*)-*'), ('ddC', '[CD2H0](=*)=*'), ('tsC', '[CD2H0](#*)-*'), ('dssC', '[CD3H0](=*)(-*)-*'), ('aasC', '[C,c;D3H0](:*)(:*)-*'), ('aaaC', '[C,c;D3H0](:*)(:*):*'), ('ssssC', '[CD4H0](-*)(-*)(-*)-*'), ('sNH3', '[ND1H3]-*'), ('sNH2', '[ND1H2]-*'), ('ssNH2', '[ND2H2](-*)-*'), ('dNH', '[ND1H]=*'), ('ssNH', '[ND2H](-*)-*'), ('aaNH', '[N,nD2H](:*):*'), ('tN', '[ND1H0]#*'), ('sssNH', '[ND3H](-*)(-*)-*'), ('dsN', '[ND2H0](=*)-*'), ('aaN', '[N,nD2H0](:*):*'), ('sssN', '[ND3H0](-*)(-*)-*'), ('ddsN', '[ND3H0](~[OD1H0])(~[OD1H0])-,:*'), # mod ('aasN', '[N,nD3H0](:*)(:*)-,:*'), # mod ('ssssN', '[ND4H0](-*)(-*)(-*)-*'), ('sOH', '[OD1H]-*'), ('dO', '[OD1H0]=*'), ('ssO', '[OD2H0](-*)-*'), ('aaO', '[O,oD2H0](:*):*'), ('sF', '[FD1]-*'), ('sSiH3', '[SiD1H3]-*'), ('ssSiH2', '[SiD2H2](-*)-*'), ('sssSiH', '[SiD3H1](-*)(-*)-*'), ('ssssSi', '[SiD4H0](-*)(-*)(-*)-*'), ('sPH2', '[PD1H2]-*'), ('ssPH', '[PD2H1](-*)-*'), ('sssP', '[PD3H0](-*)(-*)-*'), ('dsssP', '[PD4H0](=*)(-*)(-*)-*'), ('sssssP', '[PD5H0](-*)(-*)(-*)(-*)-*'), ('sSH', '[SD1H1]-*'), ('dS', '[SD1H0]=*'), ('ssS', '[SD2H0](-*)-*'), ('aaS', '[S,sD2H0](:*):*'), ('dssS', '[SD3H0](=*)(-*)-*'), ('ddssS', '[SD4H0](~[OD1H0])(~[OD1H0])(-*)-*'), # mod ('sCl', '[ClD1]-*'), ('sGeH3', '[GeD1H3](-*)'), ('ssGeH2', '[GeD2H2](-*)-*'), ('sssGeH', '[GeD3H1](-*)(-*)-*'), ('ssssGe', '[GeD4H0](-*)(-*)(-*)-*'), ('sAsH2', '[AsD1H2]-*'), ('ssAsH', '[AsD2H1](-*)-*'), ('sssAs', '[AsD3H0](-*)(-*)-*'), ('sssdAs', '[AsD4H0](=*)(-*)(-*)-*'), ('sssssAs', '[AsD5H0](-*)(-*)(-*)(-*)-*'), ('sSeH', '[SeD1H1]-*'), ('dSe', '[SeD1H0]=*'), ('ssSe', '[SeD2H0](-*)-*'), ('aaSe', '[SeD2H0](:*):*'), ('dssSe', '[SeD3H0](=*)(-*)-*'), ('ddssSe', '[SeD4H0](=*)(=*)(-*)-*'), ('sBr', '[BrD1]-*'), ('sSnH3', '[SnD1H3]-*'), ('ssSnH2', '[SnD2H2](-*)-*'), ('sssSnH', '[SnD3H1](-*)(-*)-*'), ('ssssSn', '[SnD4H0](-*)(-*)(-*)-*'), ('sI', '[ID1]-*'), ('sPbH3', '[PbD1H3]-*'), ('ssPbH2', '[PbD2H2](-*)-*'), ('sssPbH', '[PbD3H1](-*)(-*)-*'), ('ssssPb', '[PbD4H0](-*)(-*)(-*)-*'), ] esPatterns = None def BuildPatts(rawV=None): """ Internal Use Only """ global esPatterns, _rawD if rawV is None: rawV = _rawD esPatterns = [None] * len(rawV) for i, (name, sma) in enumerate(rawV): patt = Chem.MolFromSmarts(sma) if patt is None: sys.stderr.write('WARNING: problems with pattern %s (name: %s), skipped.\n' % (sma, name)) else: esPatterns[i] = name, patt def TypeAtoms(mol): """ assigns each atom in a molecule to an EState type **Returns:** list of tuples (atoms can possibly match multiple patterns) with atom types """ if esPatterns is None: BuildPatts() nAtoms = mol.GetNumAtoms() res = [None] * nAtoms for name, patt in esPatterns: matches = mol.GetSubstructMatches(patt, uniquify=0) for match in matches: idx = match[0] if res[idx] is None: res[idx] = [name] elif name not in res[idx]: res[idx].append(name) for i, v in enumerate(res): if v is not None: res[i] = tuple(v) else: res[i] = () return res
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/EState/AtomTypes.py", "copies": "12", "size": "4018", "license": "bsd-3-clause", "hash": 4815898734133917000, "line_mean": 26.9027777778, "line_max": 96, "alpha_frac": 0.4385266302, "autogenerated": false, "ratio": 2.0970772442588728, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.005109622150347409, "num_lines": 144 }
""" unit testing code for the SD file handling stuff """ import os import tempfile import unittest from rdkit import Chem from rdkit import RDConfig from rdkit.six import next class TestCase(unittest.TestCase): def setUp(self): self.fName = os.path.join(RDConfig.RDDataDir, 'NCI', 'first_200.props.sdf') with open(self.fName, 'r') as inf: inD = inf.read() self.nMolecules = inD.count('$$$$') def assertMolecule(self, mol, i): """ Assert that we have a valid molecule """ self.assertIsNotNone(mol, 'read %d failed' % i) self.assertGreater(mol.GetNumAtoms(), 0, 'no atoms in mol %d' % i) def test_SDMolSupplier(self): # tests reads using a file name (file contains 200 molecules) supp = Chem.SDMolSupplier(self.fName) # Can use as an iterator for i in range(10): mol = next(supp) self.assertMolecule(mol, i) # Can access directly i = 100 mol = supp[i - 1] self.assertMolecule(mol, i) # We can access the number of molecules self.assertEqual(len(supp), self.nMolecules, 'bad supplier length') # We know the number and can still access directly i = 12 mol = supp[i - 1] self.assertMolecule(mol, i) # Get an exception if we access an invalid number with self.assertRaises(IndexError): _ = supp[self.nMolecules] # out of bound read must fail # and we can access with negative numbers mol1 = supp[len(supp) - 1] mol2 = supp[-1] self.assertEqual(Chem.MolToSmiles(mol1), Chem.MolToSmiles(mol2)) def test_SDWriter(self): # tests writes using a file name supp = Chem.SDMolSupplier(self.fName) _, outName = tempfile.mkstemp('.sdf') writer = Chem.SDWriter(outName) m1 = next(supp) writer.SetProps(m1.GetPropNames()) for m in supp: writer.write(m) writer.flush() writer.close() # The writer does not have an explicit "close()" so need to # let the garbage collector kick in to close the file. writer = None with open(outName, 'r') as inf: outD = inf.read() # The file should be closed, but if it isn't, and this # is Windows, then the unlink() can fail. Wait and try again. try: os.unlink(outName) except Exception: import time time.sleep(1) try: os.unlink(outName) except Exception: pass self.assertEqual(self.nMolecules, outD.count('$$$$'), 'bad nMols in output') # def _testStreamRoundtrip(self): # inD = open(self.fName).read() # supp = Chem.SDMolSupplier(self.fName) # outName = tempfile.mktemp('.sdf') # writer = Chem.SDWriter(outName) # _ = next(supp) # for m in supp: # writer.write(m) # writer.flush() # writer = None # outD = open(outName, 'r').read() # try: # os.unlink(outName) # except Exception: # import time # time.sleep(1) # try: # os.unlink(outName) # except Exception: # pass # assert inD.count('$$$$') == outD.count('$$$$'), 'bad nMols in output' # io = StringIO(outD) # supp = Chem.SDMolSupplier(stream=io) # outD2 = supp.Dump() # assert outD2.count('$$$$') == len(supp), 'bad nMols in output' # assert outD2.count('$$$$') == outD.count('$$$$'), 'bad nMols in output' # assert outD2 == outD, 'bad outd' # def _testLazyDataRoundtrip(self): # inD = open(self.fName).read() # supp = Chem.SDMolSupplier(self.fName) # outName = tempfile.mktemp('.sdf') # writer = Chem.SDWriter(outName) # _ = next(supp) # for m in supp: # writer.write(m) # writer.flush() # writer = None # outD = open(outName, 'r').read() # try: # os.unlink(outName) # except Exception: # import time # time.sleep(1) # try: # os.unlink(outName) # except Exception: # pass # assert inD.count('$$$$') == outD.count('$$$$'), 'bad nMols in output' # supp = Chem.SDMolSupplier.LazySDMolSupplier(inD=outD) # outD2 = supp.Dump() # assert outD2.count('$$$$') == len(supp), 'bad nMols in output' # assert outD2.count('$$$$') == outD.count('$$$$'), 'bad nMols in output' # assert outD2 == outD, 'bad outd' # def _testLazyIter(self): # " tests lazy reads using the iterator interface " # supp = Chem.SDMolSupplier.LazySDMolSupplier(fileN=self.fName) # # nDone = 0 # for mol in supp: # assert mol, 'read %d failed' % nDone # assert mol.GetNumAtoms(), 'no atoms in mol %d' % nDone # nDone += 1 # assert nDone == 200, 'bad number of molecules: %d' % (nDone) # # l = len(supp) # assert l == 200, 'bad supplier length: %d' % (l) # # i = 12 # m = supp[i - 1] # assert m, 'back index %d failed' % i # assert m.GetNumAtoms(), 'no atoms in mol %d' % i # # try: # m = supp[201] # except IndexError: # fail = 1 # else: # fail = 0 # assert fail, 'out of bound read did not fail' if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/Suppliers/UnitTestSDMolSupplier.py", "copies": "4", "size": "5319", "license": "bsd-3-clause", "hash": -8817616385638454000, "line_mean": 28.55, "line_max": 80, "alpha_frac": 0.6036849032, "autogenerated": false, "ratio": 3.0290432801822322, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004087947701863451, "num_lines": 180 }
"""unit testing code for the SD file handling stuff """ import unittest,sys,os from rdkit import RDConfig from rdkit import Chem import tempfile from cStringIO import StringIO class TestCase(unittest.TestCase): def setUp(self): #print '\n%s: '%self.shortDescription(), self.fName = os.path.join(RDConfig.RDDataDir,'NCI','first_200.props.sdf') def _testReader(self): " tests reads using a file name " supp = Chem.SDMolSupplier(self.fName) for i in range(10): m = supp.next() assert m,'read %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i i = 100 m = supp[i-1] assert m,'read %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i l = len(supp) assert l == 200,'bad supplier length: %d'%(l) i = 12 m = supp[i-1] assert m,'back index %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i try: m = supp[201] except IndexError: fail = 1 else: fail = 0 assert fail,'out of bound read did not fail' def test_Writer(self): " tests writes using a file name " inD = open(self.fName,'r').read() supp = Chem.SDMolSupplier(self.fName) outName = tempfile.mktemp('.sdf') writer = Chem.SDWriter(outName) m1 = supp.next() writer.SetProps(m1.GetPropNames()) for m in supp: writer.write(m) writer.flush() writer = None outD = open(outName,'r').read() try: os.unlink(outName) except: import time time.sleep(1) try: os.unlink(outName) except: pass assert inD.count('$$$$')==outD.count('$$$$'),'bad nMols in output' def _testStreamRoundtrip(self): inD = open(self.fName).read() supp = Chem.SDMolSupplier(self.fName) outName = tempfile.mktemp('.sdf') writer = Chem.SDWriter(outName) m1 = supp.next() for m in supp: writer.write(m) writer.flush() writer = None outD = open(outName,'r').read() try: os.unlink(outName) except: import time time.sleep(1) try: os.unlink(outName) except: pass assert inD.count('$$$$')==outD.count('$$$$'),'bad nMols in output' io = StringIO(outD) supp = Chem.SDMolSupplier(stream=io) outD2 = supp.Dump() assert outD2.count('$$$$')==len(supp),'bad nMols in output' assert outD2.count('$$$$')==outD.count('$$$$'),'bad nMols in output' assert outD2==outD,'bad outd' def _testLazyDataRoundtrip(self): inD = open(self.fName).read() supp = Chem.SDMolSupplier(self.fName) outName = tempfile.mktemp('.sdf') writer = Chem.SDWriter(outName) m1 = supp.next() for m in supp: writer.write(m) writer.flush() writer = None outD = open(outName,'r').read() try: os.unlink(outName) except: import time time.sleep(1) try: os.unlink(outName) except: pass assert inD.count('$$$$')==outD.count('$$$$'),'bad nMols in output' supp = SDMolSupplier.LazySDMolSupplier(inD=outD) outD2 = supp.Dump() assert outD2.count('$$$$')==len(supp),'bad nMols in output' assert outD2.count('$$$$')==outD.count('$$$$'),'bad nMols in output' assert outD2==outD,'bad outd' def _testLazyIter(self): " tests lazy reads using the iterator interface " supp = SDMolSupplier.LazySDMolSupplier(fileN=self.fName) nDone = 0 for mol in supp: assert mol,'read %d failed'%i assert mol.GetNumAtoms(),'no atoms in mol %d'%i nDone += 1 assert nDone==200,'bad number of molecules: %d'%(nDone) l = len(supp) assert l == 200,'bad supplier length: %d'%(l) i = 12 m = supp[i-1] assert m,'back index %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i try: m = supp[201] except IndexError: fail = 1 else: fail = 0 assert fail,'out of bound read did not fail' if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Suppliers/UnitTestSDMolSupplier.py", "copies": "2", "size": "4271", "license": "bsd-3-clause", "hash": -1353290518686127600, "line_mean": 24.4226190476, "line_max": 77, "alpha_frac": 0.6019667525, "autogenerated": false, "ratio": 3.1497050147492627, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4751671767249263, "avg_score": null, "num_lines": null }
""" tools for interacting with chemdraw """ from __future__ import print_function import string,tempfile,os,time try: import pythoncom from win32com.client import gencache,Dispatch,constants import win32com.client.gencache cdxModule = win32com.client.gencache.EnsureModule("{5F646AAB-3B56-48D2-904C-A68D7989C251}", 0, 7, 0) except Exception: cdxModule = None _cdxVersion=0 raise ImportError("ChemDraw version (at least version 7) not found.") else: _cdxVersion=7 if cdxModule: from win32com.client import Dispatch import win32gui import re cdApp = None theDoc = None theObjs = None selectItem = None cleanItem = None centerItem = None def StartChemDraw(visible=True,openDoc=False,showDoc=False): """ launches chemdraw """ global cdApp,theDoc,theObjs,selectItem,cleanItem,centerItem if cdApp is not None: # if called more than once, do a restart holder = None selectItem = None cleanItem = None centerItem = None theObjs = None theDoc = None cdApp = None cdApp = Dispatch('ChemDraw.Application') if openDoc: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects else: theDoc = None selectItem = cdApp.MenuBars(1).Menus(2).MenuItems(8) cleanItem = cdApp.MenuBars(1).Menus(5).MenuItems(6) if _cdxVersion == 6: centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(1) else: centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(7) if visible: cdApp.Visible=1 if theDoc and showDoc: theDoc.Activate() def ReactivateChemDraw(openDoc=True,showDoc=True): global cdApp,theDoc,theObjs cdApp.Visible=1 if openDoc: theDoc = cdApp.Documents.Add() if theDoc and showDoc: theDoc.Activate() theObjs = theDoc.Objects # ------------------------------------------------------------------ # interactions with Chemdraw # ------------------------------------------------------------------ def CDXConvert(inData,inFormat,outFormat): """converts the data passed in from one format to another inFormat should be one of the following: chemical/x-cdx chemical/cdx chemical/x-daylight-smiles chemical/daylight-smiles chemical/x-mdl-isis chemical/mdl-isis chemical/x-mdl-molfile chemical/mdl-molfile chemical/x-mdl-rxn chemical/mdl-rxn chemical/x-mdl-tgf chemical/mdl-tgf chemical/x-questel-F1 chemical/x-questel-F1-query outFormat should be one of the preceding or: image/x-png image/png image/x-wmf image/wmf image/tiff application/postscript image/gif """ global theObjs,theDoc if cdApp is None: StartChemDraw() if theObjs is None: if theDoc is None: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects theObjs.SetData(inFormat,inData,pythoncom.Missing) outD = theObjs.GetData(outFormat) theObjs.Clear() return outD def CDXClean(inData,inFormat,outFormat): """calls the CDXLib Clean function on the data passed in. CDXLib_Clean attempts to clean (prettify) the data before doing an output conversion. It can be thought of as CDXConvert++. CDXClean supports the same input and output specifiers as CDXConvert (see above) """ global cdApp,theDoc,theObjs,selectItem,cleanItem if cdApp is None: StartChemDraw() if theObjs is None: if theDoc is None: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects theObjs.SetData(inFormat,inData,pythoncom.Missing) theObjs.Select() cleanItem.Execute() outD = theObjs.GetData(outFormat) theObjs.Clear() return outD def CDXDisplay(inData,inFormat='chemical/cdx',clear=1): """ displays the data in Chemdraw """ global cdApp,theDoc,theObjs,selectItem,cleanItem,centerItem if cdApp is None: StartChemDraw() try: theDoc.Activate() except Exception: ReactivateChemDraw() theObjs = theDoc.Objects if clear: theObjs.Clear() theObjs.SetData(inFormat,inData,pythoncom.Missing) return def CDXGrab(outFormat='chemical/x-mdl-molfile'): """ returns the contents of the active chemdraw document """ global cdApp,theDoc if cdApp is None: res = "" else: cdApp.Visible=1 if not cdApp.ActiveDocument: ReactivateChemDraw() try: res = cdApp.ActiveDocument.Objects.GetData(outFormat) except Exception: res = "" return res def CloseChemdraw(): """ shuts down chemdraw """ global cdApp try: cdApp.Quit() except Exception: pass Exit() def Exit(): """ destroys our link to Chemdraw """ global cdApp cdApp = None def SaveChemDrawDoc(fileName='save.cdx'): """force chemdraw to save the active document NOTE: the extension of the filename will determine the format used to save the file. """ d = cdApp.ActiveDocument d.SaveAs(fileName) def CloseChemDrawDoc(): """force chemdraw to save the active document NOTE: the extension of the filename will determine the format used to save the file. """ d = cdApp.ActiveDocument d.Close() def RaiseWindowNamed(nameRe): # start by getting a list of all the windows: cb = lambda x,y: y.append(x) wins = [] win32gui.EnumWindows(cb,wins) # now check to see if any match our regexp: tgtWin = -1 for win in wins: txt = win32gui.GetWindowText(win) if nameRe.match(txt): tgtWin=win break if tgtWin>=0: win32gui.ShowWindow(tgtWin,1) win32gui.BringWindowToTop(tgtWin) def RaiseChemDraw(): e = re.compile('^ChemDraw') RaiseWindowNamed(e) try: from PIL import Image from io import StringIO def SmilesToPilImage(smilesStr): """takes a SMILES string and returns a PIL image using chemdraw """ return MolToPilImage(smilesStr,inFormat='chemical/daylight-smiles',outFormat='image/gif') def MolToPilImage(dataStr,inFormat='chemical/daylight-smiles',outFormat='image/gif'): """takes a molecule string and returns a PIL image using chemdraw """ # do the conversion... res = CDXConvert(dataStr,inFormat,outFormat) dataFile = StringIO(str(res)) img = Image.open(dataFile).convert('RGB') return img except ImportError: def SmilesToPilImage(smilesStr): print('You need to have PIL installed to use this functionality') return None def MolToPilImage(dataStr,inFormat='chemical/daylight-smiles',outFormat='image/gif'): print('You need to have PIL installed to use this functionality') return None # ------------------------------------------------------------------ # interactions with Chem3D # ------------------------------------------------------------------ c3dApp = None def StartChem3D(visible=0): """ launches Chem3D """ global c3dApp c3dApp = Dispatch('Chem3D.Application') if not c3dApp.Visible: c3dApp.Visible = visible def CloseChem3D(): """ shuts down Chem3D """ global c3dApp c3dApp.Quit() c3dApp = None availChem3DProps = ('DipoleMoment','BendEnergy','Non14VDWEnergy','StericEnergy', 'StretchBendEnergy','StretchEnergy','TorsionEnergy','VDW14Energy') def Add3DCoordsToMol(data,format,props={}): """ adds 3D coordinates to the data passed in using Chem3D **Arguments** - data: the molecular data - format: the format of _data_. Should be something accepted by _CDXConvert_ - props: (optional) a dictionary used to return calculated properties """ global c3dApp if c3dApp is None: StartChem3D() if format != 'chemical/mdl-molfile': molData = CDXClean(data,format,'chemical/mdl-molfile') else: molData = data molFName = tempfile.mktemp('.mol') open(molFName,'wb+').write(molData) doc = c3dApp.Documents.Open(molFName) if not doc: print('cannot open molecule') raise ValueError('No Molecule') # set up the MM2 job job = Dispatch('Chem3D.MM2Job') job.Type=1 job.DisplayEveryIteration=0 job.RecordEveryIteration=0 # start the calculation... doc.MM2Compute(job) # and wait for it to finish while doc.ComputeStatus in [0x434f4d50,0x50454e44]: pass #outFName = tempfile.mktemp('.mol') # this is horrible, but apparently Chem3D gets pissy with tempfiles: outFName = os.getcwd()+'/to3d.mol' doc.SaveAs(outFName) # generate the properties for prop in availChem3DProps: props[prop] = eval('doc.%s'%prop) doc.Close(0) os.unlink(molFName) c3dData = open(outFName,'r').read() gone = 0 while not gone: try: os.unlink(outFName) except Exception: time.sleep(.5) else: gone = 1 return c3dData def OptimizeSDFile(inFileName,outFileName,problemFileName='problems.sdf', restartEvery=20): """ optimizes the structure of every molecule in the input SD file **Arguments** - inFileName: name of the input SD file - outFileName: name of the output SD file - problemFileName: (optional) name of the SD file used to store molecules which fail during the optimization process - restartEvery: (optional) Chem3D will be shut down and restarted every _restartEvery_ molecules to try and keep core leaks under control """ inFile = open(inFileName,'r') outFile = open(outFileName,'w+') problemFile = None props = {} lines = [] nextLine = inFile.readline() skip = 0 nDone = 0 t1 = time.time() while nextLine != '': if nextLine.find('M END') != -1: lines.append(nextLine) molBlock = string.join(lines,'') try: newMolBlock = Add3DCoordsToMol(molBlock,'chemical/mdl-molfile',props=props) except Exception: badBlock = molBlock skip = 1 lines = [] else: skip = 0 lines = [newMolBlock] elif nextLine.find('$$$$') != -1: t2 = time.time() nDone += 1 print('finished molecule %d in %f seconds'%(nDone,time.time()-t1)) t1 = time.time() if nDone%restartEvery == 0: CloseChem3D() StartChem3D() outFile.close() outFile = open(outFileName,'a') if not skip: for prop in props.keys(): lines.append('> <%s>\n%f\n\n'%(prop,props[prop])) lines.append(nextLine) outFile.write(string.join(lines,'')) lines = [] else: skip = 0 lines.append(nextLine) if problemFile is None: problemFile = open(problemFileName,'w+') problemFile.write(badBlock) problemFile.write(string.join(lines,'')) lines = [] else: lines.append(nextLine) nextLine = inFile.readline() outFile.close() if problemFile is not None: problemFile.close() if __name__=='__main__': inStr = 'CCC(C=O)CCC' img = SmilesToPilImage(inStr) img.save('foo.jpg') convStr = CDXClean(inStr,'chemical/x-daylight-smiles','chemical/x-daylight-smiles') print('in:',inStr) print('out:',convStr) convStr = CDXConvert(inStr,'chemical/x-daylight-smiles','chemical/x-mdl-molfile') print('in:',inStr) print('out:',convStr) convStr2 = CDXClean(convStr,'chemical/x-mdl-molfile','chemical/x-mdl-molfile') print('out2:',convStr2) inStr = 'COc1ccc(c2onc(c2C(=O)NCCc3ccc(F)cc3)c4ccc(F)cc4)c(OC)c1' convStr = CDXConvert(inStr,'chemical/x-daylight-smiles','chemical/x-mdl-molfile') out = open('test.mol','w+') out.write(convStr) out.close()
{ "repo_name": "adalke/rdkit", "path": "rdkit/utils/chemdraw.py", "copies": "1", "size": "11711", "license": "bsd-3-clause", "hash": 1579553171053144300, "line_mean": 26.3621495327, "line_max": 102, "alpha_frac": 0.6540859021, "autogenerated": false, "ratio": 3.278555431131019, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9279102036682836, "avg_score": 0.030707859309636817, "num_lines": 428 }
""" tools for interacting with chemdraw """ from __future__ import print_function import string, tempfile, os, time try: import pythoncom from win32com.client import gencache, Dispatch, constants import win32com.client.gencache cdxModule = win32com.client.gencache.EnsureModule("{5F646AAB-3B56-48D2-904C-A68D7989C251}", 0, 7, 0) except Exception: cdxModule = None _cdxVersion = 0 raise ImportError("ChemDraw version (at least version 7) not found.") else: _cdxVersion = 7 if cdxModule: from win32com.client import Dispatch import win32gui import re cdApp = None theDoc = None theObjs = None selectItem = None cleanItem = None centerItem = None def StartChemDraw(visible=True, openDoc=False, showDoc=False): """ launches chemdraw """ global cdApp, theDoc, theObjs, selectItem, cleanItem, centerItem if cdApp is not None: # if called more than once, do a restart holder = None selectItem = None cleanItem = None centerItem = None theObjs = None theDoc = None cdApp = None cdApp = Dispatch('ChemDraw.Application') if openDoc: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects else: theDoc = None selectItem = cdApp.MenuBars(1).Menus(2).MenuItems(8) cleanItem = cdApp.MenuBars(1).Menus(5).MenuItems(6) if _cdxVersion == 6: centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(1) else: centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(7) if visible: cdApp.Visible = 1 if theDoc and showDoc: theDoc.Activate() def ReactivateChemDraw(openDoc=True, showDoc=True): global cdApp, theDoc, theObjs cdApp.Visible = 1 if openDoc: theDoc = cdApp.Documents.Add() if theDoc and showDoc: theDoc.Activate() theObjs = theDoc.Objects # ------------------------------------------------------------------ # interactions with Chemdraw # ------------------------------------------------------------------ def CDXConvert(inData, inFormat, outFormat): """converts the data passed in from one format to another inFormat should be one of the following: chemical/x-cdx chemical/cdx chemical/x-daylight-smiles chemical/daylight-smiles chemical/x-mdl-isis chemical/mdl-isis chemical/x-mdl-molfile chemical/mdl-molfile chemical/x-mdl-rxn chemical/mdl-rxn chemical/x-mdl-tgf chemical/mdl-tgf chemical/x-questel-F1 chemical/x-questel-F1-query outFormat should be one of the preceding or: image/x-png image/png image/x-wmf image/wmf image/tiff application/postscript image/gif """ global theObjs, theDoc if cdApp is None: StartChemDraw() if theObjs is None: if theDoc is None: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects theObjs.SetData(inFormat, inData, pythoncom.Missing) outD = theObjs.GetData(outFormat) theObjs.Clear() return outD def CDXClean(inData, inFormat, outFormat): """calls the CDXLib Clean function on the data passed in. CDXLib_Clean attempts to clean (prettify) the data before doing an output conversion. It can be thought of as CDXConvert++. CDXClean supports the same input and output specifiers as CDXConvert (see above) """ global cdApp, theDoc, theObjs, selectItem, cleanItem if cdApp is None: StartChemDraw() if theObjs is None: if theDoc is None: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects theObjs.SetData(inFormat, inData, pythoncom.Missing) theObjs.Select() cleanItem.Execute() outD = theObjs.GetData(outFormat) theObjs.Clear() return outD def CDXDisplay(inData, inFormat='chemical/cdx', clear=1): """ displays the data in Chemdraw """ global cdApp, theDoc, theObjs, selectItem, cleanItem, centerItem if cdApp is None: StartChemDraw() try: theDoc.Activate() except Exception: ReactivateChemDraw() theObjs = theDoc.Objects if clear: theObjs.Clear() theObjs.SetData(inFormat, inData, pythoncom.Missing) return def CDXGrab(outFormat='chemical/x-mdl-molfile'): """ returns the contents of the active chemdraw document """ global cdApp, theDoc if cdApp is None: res = "" else: cdApp.Visible = 1 if not cdApp.ActiveDocument: ReactivateChemDraw() try: res = cdApp.ActiveDocument.Objects.GetData(outFormat) except Exception: res = "" return res def CloseChemdraw(): """ shuts down chemdraw """ global cdApp try: cdApp.Quit() except Exception: pass Exit() def Exit(): """ destroys our link to Chemdraw """ global cdApp cdApp = None def SaveChemDrawDoc(fileName='save.cdx'): """force chemdraw to save the active document NOTE: the extension of the filename will determine the format used to save the file. """ d = cdApp.ActiveDocument d.SaveAs(fileName) def CloseChemDrawDoc(): """force chemdraw to save the active document NOTE: the extension of the filename will determine the format used to save the file. """ d = cdApp.ActiveDocument d.Close() def RaiseWindowNamed(nameRe): # start by getting a list of all the windows: cb = lambda x, y: y.append(x) wins = [] win32gui.EnumWindows(cb, wins) # now check to see if any match our regexp: tgtWin = -1 for win in wins: txt = win32gui.GetWindowText(win) if nameRe.match(txt): tgtWin = win break if tgtWin >= 0: win32gui.ShowWindow(tgtWin, 1) win32gui.BringWindowToTop(tgtWin) def RaiseChemDraw(): e = re.compile('^ChemDraw') RaiseWindowNamed(e) try: from PIL import Image from io import StringIO def SmilesToPilImage(smilesStr): """takes a SMILES string and returns a PIL image using chemdraw """ return MolToPilImage(smilesStr, inFormat='chemical/daylight-smiles', outFormat='image/gif') def MolToPilImage(dataStr, inFormat='chemical/daylight-smiles', outFormat='image/gif'): """takes a molecule string and returns a PIL image using chemdraw """ # do the conversion... res = CDXConvert(dataStr, inFormat, outFormat) dataFile = StringIO(str(res)) img = Image.open(dataFile).convert('RGB') return img except ImportError: def SmilesToPilImage(smilesStr): print('You need to have PIL installed to use this functionality') return None def MolToPilImage(dataStr, inFormat='chemical/daylight-smiles', outFormat='image/gif'): print('You need to have PIL installed to use this functionality') return None # ------------------------------------------------------------------ # interactions with Chem3D # ------------------------------------------------------------------ c3dApp = None def StartChem3D(visible=0): """ launches Chem3D """ global c3dApp c3dApp = Dispatch('Chem3D.Application') if not c3dApp.Visible: c3dApp.Visible = visible def CloseChem3D(): """ shuts down Chem3D """ global c3dApp c3dApp.Quit() c3dApp = None availChem3DProps = ('DipoleMoment', 'BendEnergy', 'Non14VDWEnergy', 'StericEnergy', 'StretchBendEnergy', 'StretchEnergy', 'TorsionEnergy', 'VDW14Energy') def Add3DCoordsToMol(data, format, props={}): """ adds 3D coordinates to the data passed in using Chem3D **Arguments** - data: the molecular data - format: the format of _data_. Should be something accepted by _CDXConvert_ - props: (optional) a dictionary used to return calculated properties """ global c3dApp if c3dApp is None: StartChem3D() if format != 'chemical/mdl-molfile': molData = CDXClean(data, format, 'chemical/mdl-molfile') else: molData = data molFName = tempfile.mktemp('.mol') open(molFName, 'wb+').write(molData) doc = c3dApp.Documents.Open(molFName) if not doc: print('cannot open molecule') raise ValueError('No Molecule') # set up the MM2 job job = Dispatch('Chem3D.MM2Job') job.Type = 1 job.DisplayEveryIteration = 0 job.RecordEveryIteration = 0 # start the calculation... doc.MM2Compute(job) # and wait for it to finish while doc.ComputeStatus in [0x434f4d50, 0x50454e44]: pass #outFName = tempfile.mktemp('.mol') # this is horrible, but apparently Chem3D gets pissy with tempfiles: outFName = os.getcwd() + '/to3d.mol' doc.SaveAs(outFName) # generate the properties for prop in availChem3DProps: props[prop] = eval('doc.%s' % prop) doc.Close(0) os.unlink(molFName) c3dData = open(outFName, 'r').read() gone = 0 while not gone: try: os.unlink(outFName) except Exception: time.sleep(.5) else: gone = 1 return c3dData def OptimizeSDFile(inFileName, outFileName, problemFileName='problems.sdf', restartEvery=20): """ optimizes the structure of every molecule in the input SD file **Arguments** - inFileName: name of the input SD file - outFileName: name of the output SD file - problemFileName: (optional) name of the SD file used to store molecules which fail during the optimization process - restartEvery: (optional) Chem3D will be shut down and restarted every _restartEvery_ molecules to try and keep core leaks under control """ inFile = open(inFileName, 'r') outFile = open(outFileName, 'w+') problemFile = None props = {} lines = [] nextLine = inFile.readline() skip = 0 nDone = 0 t1 = time.time() while nextLine != '': if nextLine.find('M END') != -1: lines.append(nextLine) molBlock = string.join(lines, '') try: newMolBlock = Add3DCoordsToMol(molBlock, 'chemical/mdl-molfile', props=props) except Exception: badBlock = molBlock skip = 1 lines = [] else: skip = 0 lines = [newMolBlock] elif nextLine.find('$$$$') != -1: t2 = time.time() nDone += 1 print('finished molecule %d in %f seconds' % (nDone, time.time() - t1)) t1 = time.time() if nDone % restartEvery == 0: CloseChem3D() StartChem3D() outFile.close() outFile = open(outFileName, 'a') if not skip: for prop in props.keys(): lines.append('> <%s>\n%f\n\n' % (prop, props[prop])) lines.append(nextLine) outFile.write(string.join(lines, '')) lines = [] else: skip = 0 lines.append(nextLine) if problemFile is None: problemFile = open(problemFileName, 'w+') problemFile.write(badBlock) problemFile.write(string.join(lines, '')) lines = [] else: lines.append(nextLine) nextLine = inFile.readline() outFile.close() if problemFile is not None: problemFile.close() if __name__ == '__main__': inStr = 'CCC(C=O)CCC' img = SmilesToPilImage(inStr) img.save('foo.jpg') convStr = CDXClean(inStr, 'chemical/x-daylight-smiles', 'chemical/x-daylight-smiles') print('in:', inStr) print('out:', convStr) convStr = CDXConvert(inStr, 'chemical/x-daylight-smiles', 'chemical/x-mdl-molfile') print('in:', inStr) print('out:', convStr) convStr2 = CDXClean(convStr, 'chemical/x-mdl-molfile', 'chemical/x-mdl-molfile') print('out2:', convStr2) inStr = 'COc1ccc(c2onc(c2C(=O)NCCc3ccc(F)cc3)c4ccc(F)cc4)c(OC)c1' convStr = CDXConvert(inStr, 'chemical/x-daylight-smiles', 'chemical/x-mdl-molfile') out = open('test.mol', 'w+') out.write(convStr) out.close()
{ "repo_name": "jandom/rdkit", "path": "rdkit/utils/chemdraw.py", "copies": "1", "size": "11869", "license": "bsd-3-clause", "hash": 7721305097626846000, "line_mean": 25.4933035714, "line_max": 99, "alpha_frac": 0.6453787177, "autogenerated": false, "ratio": 3.2969444444444442, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.93413107287757, "avg_score": 0.020202486673748802, "num_lines": 448 }
""" tools for interacting with chemdraw """ from __future__ import print_function import tempfile, os, time try: import pythoncom from win32com.client import gencache, Dispatch, constants import win32com.client.gencache cdxModule = win32com.client.gencache.EnsureModule("{5F646AAB-3B56-48D2-904C-A68D7989C251}", 0, 7, 0) except Exception: cdxModule = None _cdxVersion = 0 raise ImportError("ChemDraw version (at least version 7) not found.") else: _cdxVersion = 7 if cdxModule: from win32com.client import Dispatch import win32gui import re cdApp = None theDoc = None theObjs = None selectItem = None cleanItem = None centerItem = None def StartChemDraw(visible=True, openDoc=False, showDoc=False): """ launches chemdraw """ global cdApp, theDoc, theObjs, selectItem, cleanItem, centerItem if cdApp is not None: # if called more than once, do a restart holder = None selectItem = None cleanItem = None centerItem = None theObjs = None theDoc = None cdApp = None cdApp = Dispatch('ChemDraw.Application') if openDoc: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects else: theDoc = None selectItem = cdApp.MenuBars(1).Menus(2).MenuItems(8) cleanItem = cdApp.MenuBars(1).Menus(5).MenuItems(6) if _cdxVersion == 6: centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(1) else: centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(7) if visible: cdApp.Visible = 1 if theDoc and showDoc: theDoc.Activate() def ReactivateChemDraw(openDoc=True, showDoc=True): global cdApp, theDoc, theObjs cdApp.Visible = 1 if openDoc: theDoc = cdApp.Documents.Add() if theDoc and showDoc: theDoc.Activate() theObjs = theDoc.Objects # ------------------------------------------------------------------ # interactions with Chemdraw # ------------------------------------------------------------------ def CDXConvert(inData, inFormat, outFormat): """converts the data passed in from one format to another inFormat should be one of the following: chemical/x-cdx chemical/cdx chemical/x-daylight-smiles chemical/daylight-smiles chemical/x-mdl-isis chemical/mdl-isis chemical/x-mdl-molfile chemical/mdl-molfile chemical/x-mdl-rxn chemical/mdl-rxn chemical/x-mdl-tgf chemical/mdl-tgf chemical/x-questel-F1 chemical/x-questel-F1-query outFormat should be one of the preceding or: image/x-png image/png image/x-wmf image/wmf image/tiff application/postscript image/gif """ global theObjs, theDoc if cdApp is None: StartChemDraw() if theObjs is None: if theDoc is None: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects theObjs.SetData(inFormat, inData, pythoncom.Missing) outD = theObjs.GetData(outFormat) theObjs.Clear() return outD def CDXClean(inData, inFormat, outFormat): """calls the CDXLib Clean function on the data passed in. CDXLib_Clean attempts to clean (prettify) the data before doing an output conversion. It can be thought of as CDXConvert++. CDXClean supports the same input and output specifiers as CDXConvert (see above) """ global cdApp, theDoc, theObjs, selectItem, cleanItem if cdApp is None: StartChemDraw() if theObjs is None: if theDoc is None: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects theObjs.SetData(inFormat, inData, pythoncom.Missing) theObjs.Select() cleanItem.Execute() outD = theObjs.GetData(outFormat) theObjs.Clear() return outD def CDXDisplay(inData, inFormat='chemical/cdx', clear=1): """ displays the data in Chemdraw """ global cdApp, theDoc, theObjs, selectItem, cleanItem, centerItem if cdApp is None: StartChemDraw() try: theDoc.Activate() except Exception: ReactivateChemDraw() theObjs = theDoc.Objects if clear: theObjs.Clear() theObjs.SetData(inFormat, inData, pythoncom.Missing) return def CDXGrab(outFormat='chemical/x-mdl-molfile'): """ returns the contents of the active chemdraw document """ global cdApp, theDoc if cdApp is None: res = "" else: cdApp.Visible = 1 if not cdApp.ActiveDocument: ReactivateChemDraw() try: res = cdApp.ActiveDocument.Objects.GetData(outFormat) except Exception: res = "" return res def CloseChemdraw(): """ shuts down chemdraw """ global cdApp try: cdApp.Quit() except Exception: pass Exit() def Exit(): """ destroys our link to Chemdraw """ global cdApp cdApp = None def SaveChemDrawDoc(fileName='save.cdx'): """force chemdraw to save the active document NOTE: the extension of the filename will determine the format used to save the file. """ d = cdApp.ActiveDocument d.SaveAs(fileName) def CloseChemDrawDoc(): """force chemdraw to save the active document NOTE: the extension of the filename will determine the format used to save the file. """ d = cdApp.ActiveDocument d.Close() def RaiseWindowNamed(nameRe): # start by getting a list of all the windows: cb = lambda x, y: y.append(x) wins = [] win32gui.EnumWindows(cb, wins) # now check to see if any match our regexp: tgtWin = -1 for win in wins: txt = win32gui.GetWindowText(win) if nameRe.match(txt): tgtWin = win break if tgtWin >= 0: win32gui.ShowWindow(tgtWin, 1) win32gui.BringWindowToTop(tgtWin) def RaiseChemDraw(): e = re.compile('^ChemDraw') RaiseWindowNamed(e) try: from PIL import Image from io import StringIO def SmilesToPilImage(smilesStr): """takes a SMILES string and returns a PIL image using chemdraw """ return MolToPilImage(smilesStr, inFormat='chemical/daylight-smiles', outFormat='image/gif') def MolToPilImage(dataStr, inFormat='chemical/daylight-smiles', outFormat='image/gif'): """takes a molecule string and returns a PIL image using chemdraw """ # do the conversion... res = CDXConvert(dataStr, inFormat, outFormat) dataFile = StringIO(str(res)) img = Image.open(dataFile).convert('RGB') return img except ImportError: def SmilesToPilImage(smilesStr): print('You need to have PIL installed to use this functionality') return None def MolToPilImage(dataStr, inFormat='chemical/daylight-smiles', outFormat='image/gif'): print('You need to have PIL installed to use this functionality') return None # ------------------------------------------------------------------ # interactions with Chem3D # ------------------------------------------------------------------ c3dApp = None def StartChem3D(visible=0): """ launches Chem3D """ global c3dApp c3dApp = Dispatch('Chem3D.Application') if not c3dApp.Visible: c3dApp.Visible = visible def CloseChem3D(): """ shuts down Chem3D """ global c3dApp c3dApp.Quit() c3dApp = None availChem3DProps = ('DipoleMoment', 'BendEnergy', 'Non14VDWEnergy', 'StericEnergy', 'StretchBendEnergy', 'StretchEnergy', 'TorsionEnergy', 'VDW14Energy') def Add3DCoordsToMol(data, format, props={}): """ adds 3D coordinates to the data passed in using Chem3D **Arguments** - data: the molecular data - format: the format of _data_. Should be something accepted by _CDXConvert_ - props: (optional) a dictionary used to return calculated properties """ global c3dApp if c3dApp is None: StartChem3D() if format != 'chemical/mdl-molfile': molData = CDXClean(data, format, 'chemical/mdl-molfile') else: molData = data molFName = tempfile.mktemp('.mol') open(molFName, 'wb+').write(molData) doc = c3dApp.Documents.Open(molFName) if not doc: print('cannot open molecule') raise ValueError('No Molecule') # set up the MM2 job job = Dispatch('Chem3D.MM2Job') job.Type = 1 job.DisplayEveryIteration = 0 job.RecordEveryIteration = 0 # start the calculation... doc.MM2Compute(job) # and wait for it to finish while doc.ComputeStatus in [0x434f4d50, 0x50454e44]: pass #outFName = tempfile.mktemp('.mol') # this is horrible, but apparently Chem3D gets pissy with tempfiles: outFName = os.getcwd() + '/to3d.mol' doc.SaveAs(outFName) # generate the properties for prop in availChem3DProps: props[prop] = eval('doc.%s' % prop) doc.Close(0) os.unlink(molFName) c3dData = open(outFName, 'r').read() gone = 0 while not gone: try: os.unlink(outFName) except Exception: time.sleep(.5) else: gone = 1 return c3dData def OptimizeSDFile(inFileName, outFileName, problemFileName='problems.sdf', restartEvery=20): """ optimizes the structure of every molecule in the input SD file **Arguments** - inFileName: name of the input SD file - outFileName: name of the output SD file - problemFileName: (optional) name of the SD file used to store molecules which fail during the optimization process - restartEvery: (optional) Chem3D will be shut down and restarted every _restartEvery_ molecules to try and keep core leaks under control """ inFile = open(inFileName, 'r') outFile = open(outFileName, 'w+') problemFile = None props = {} lines = [] nextLine = inFile.readline() skip = 0 nDone = 0 t1 = time.time() while nextLine != '': if nextLine.find('M END') != -1: lines.append(nextLine) molBlock = ''.join(lines) try: newMolBlock = Add3DCoordsToMol(molBlock, 'chemical/mdl-molfile', props=props) except Exception: badBlock = molBlock skip = 1 lines = [] else: skip = 0 lines = [newMolBlock] elif nextLine.find('$$$$') != -1: t2 = time.time() nDone += 1 print('finished molecule %d in %f seconds' % (nDone, time.time() - t1)) t1 = time.time() if nDone % restartEvery == 0: CloseChem3D() StartChem3D() outFile.close() outFile = open(outFileName, 'a') if not skip: for prop in props.keys(): lines.append('> <%s>\n%f\n\n' % (prop, props[prop])) lines.append(nextLine) outFile.write(''.join(lines)) lines = [] else: skip = 0 lines.append(nextLine) if problemFile is None: problemFile = open(problemFileName, 'w+') problemFile.write(badBlock) problemFile.write(''.join(lines)) lines = [] else: lines.append(nextLine) nextLine = inFile.readline() outFile.close() if problemFile is not None: problemFile.close() if __name__ == '__main__': inStr = 'CCC(C=O)CCC' img = SmilesToPilImage(inStr) img.save('foo.jpg') convStr = CDXClean(inStr, 'chemical/x-daylight-smiles', 'chemical/x-daylight-smiles') print('in:', inStr) print('out:', convStr) convStr = CDXConvert(inStr, 'chemical/x-daylight-smiles', 'chemical/x-mdl-molfile') print('in:', inStr) print('out:', convStr) convStr2 = CDXClean(convStr, 'chemical/x-mdl-molfile', 'chemical/x-mdl-molfile') print('out2:', convStr2) inStr = 'COc1ccc(c2onc(c2C(=O)NCCc3ccc(F)cc3)c4ccc(F)cc4)c(OC)c1' convStr = CDXConvert(inStr, 'chemical/x-daylight-smiles', 'chemical/x-mdl-molfile') out = open('test.mol', 'w+') out.write(convStr) out.close()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/utils/chemdraw.py", "copies": "4", "size": "11837", "license": "bsd-3-clause", "hash": 4634962496583773000, "line_mean": 25.421875, "line_max": 99, "alpha_frac": 0.6450958858, "autogenerated": false, "ratio": 3.2972144846796656, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.02023663795445339, "num_lines": 448 }
""" tools for interacting with chemdraw """ import string,tempfile,os,time try: import pythoncom from win32com.client import gencache,Dispatch,constants import win32com.client.gencache cdxModule = win32com.client.gencache.EnsureModule("{5F646AAB-3B56-48D2-904C-A68D7989C251}", 0, 7, 0) except: cdxModule = None _cdxVersion=0 raise ImportError,"ChemDraw version (at least version 7) not found." else: _cdxVersion=7 if cdxModule: from win32com.client import Dispatch import win32gui import re cdApp = None theDoc = None theObjs = None selectItem = None cleanItem = None centerItem = None def StartChemDraw(visible=True,openDoc=False,showDoc=False): """ launches chemdraw """ global cdApp,theDoc,theObjs,selectItem,cleanItem,centerItem if cdApp is not None: # if called more than once, do a restart holder = None selectItem = None cleanItem = None centerItem = None theObjs = None theDoc = None cdApp = None cdApp = Dispatch('ChemDraw.Application') if openDoc: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects else: theDoc = None selectItem = cdApp.MenuBars(1).Menus(2).MenuItems(8) cleanItem = cdApp.MenuBars(1).Menus(5).MenuItems(6) if _cdxVersion == 6: centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(1) else: centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(7) if visible: cdApp.Visible=1 if theDoc and showDoc: theDoc.Activate() def ReactivateChemDraw(openDoc=True,showDoc=True): global cdApp,theDoc,theObjs cdApp.Visible=1 if openDoc: theDoc = cdApp.Documents.Add() if theDoc and showDoc: theDoc.Activate() theObjs = theDoc.Objects # ------------------------------------------------------------------ # interactions with Chemdraw # ------------------------------------------------------------------ def CDXConvert(inData,inFormat,outFormat): """converts the data passed in from one format to another inFormat should be one of the following: chemical/x-cdx chemical/cdx chemical/x-daylight-smiles chemical/daylight-smiles chemical/x-mdl-isis chemical/mdl-isis chemical/x-mdl-molfile chemical/mdl-molfile chemical/x-mdl-rxn chemical/mdl-rxn chemical/x-mdl-tgf chemical/mdl-tgf chemical/x-questel-F1 chemical/x-questel-F1-query outFormat should be one of the preceding or: image/x-png image/png image/x-wmf image/wmf image/tiff application/postscript image/gif """ global theObjs,theDoc if cdApp is None: StartChemDraw() if theObjs is None: if theDoc is None: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects theObjs.SetData(inFormat,inData,pythoncom.Missing) outD = theObjs.GetData(outFormat) theObjs.Clear() return outD def CDXClean(inData,inFormat,outFormat): """calls the CDXLib Clean function on the data passed in. CDXLib_Clean attempts to clean (prettify) the data before doing an output conversion. It can be thought of as CDXConvert++. CDXClean supports the same input and output specifiers as CDXConvert (see above) """ global cdApp,theDoc,theObjs,selectItem,cleanItem if cdApp is None: StartChemDraw() if theObjs is None: if theDoc is None: theDoc = cdApp.Documents.Add() theObjs = theDoc.Objects theObjs.SetData(inFormat,inData,pythoncom.Missing) theObjs.Select() cleanItem.Execute() outD = theObjs.GetData(outFormat) theObjs.Clear() return outD def CDXDisplay(inData,inFormat='chemical/cdx',clear=1): """ displays the data in Chemdraw """ global cdApp,theDoc,theObjs,selectItem,cleanItem,centerItem if cdApp is None: StartChemDraw() try: theDoc.Activate() except: ReactivateChemDraw() theObjs = theDoc.Objects if clear: theObjs.Clear() theObjs.SetData(inFormat,inData,pythoncom.Missing) return def CDXGrab(outFormat='chemical/x-mdl-molfile'): """ returns the contents of the active chemdraw document """ global cdApp,theDoc if cdApp is None: res = "" else: cdApp.Visible=1 if not cdApp.ActiveDocument: ReactivateChemDraw() try: res = cdApp.ActiveDocument.Objects.GetData(outFormat) except: res = "" return res def CloseChemdraw(): """ shuts down chemdraw """ global cdApp try: cdApp.Quit() except: pass Exit() def Exit(): """ destroys our link to Chemdraw """ global cdApp cdApp = None def SaveChemDrawDoc(fileName='save.cdx'): """force chemdraw to save the active document NOTE: the extension of the filename will determine the format used to save the file. """ d = cdApp.ActiveDocument d.SaveAs(fileName) def CloseChemDrawDoc(): """force chemdraw to save the active document NOTE: the extension of the filename will determine the format used to save the file. """ d = cdApp.ActiveDocument d.Close() def RaiseWindowNamed(nameRe): # start by getting a list of all the windows: cb = lambda x,y: y.append(x) wins = [] win32gui.EnumWindows(cb,wins) # now check to see if any match our regexp: tgtWin = -1 for win in wins: txt = win32gui.GetWindowText(win) if nameRe.match(txt): tgtWin=win break if tgtWin>=0: win32gui.ShowWindow(tgtWin,1) win32gui.BringWindowToTop(tgtWin) def RaiseChemDraw(): e = re.compile('^ChemDraw') RaiseWindowNamed(e) try: from PIL import Image import cStringIO def SmilesToPilImage(smilesStr): """takes a SMILES string and returns a PIL image using chemdraw """ return MolToPilImage(smilesStr,inFormat='chemical/daylight-smiles',outFormat='image/gif') def MolToPilImage(dataStr,inFormat='chemical/daylight-smiles',outFormat='image/gif'): """takes a molecule string and returns a PIL image using chemdraw """ # do the conversion... res = CDXConvert(dataStr,inFormat,outFormat) dataFile = cStringIO.StringIO(str(res)) img = Image.open(dataFile).convert('RGB') return img except ImportError: def SmilesToPilImage(smilesStr): print 'You need to have PIL installed to use this functionality' return None def MolToPilImage(dataStr,inFormat='chemical/daylight-smiles',outFormat='image/gif'): print 'You need to have PIL installed to use this functionality' return None # ------------------------------------------------------------------ # interactions with Chem3D # ------------------------------------------------------------------ c3dApp = None def StartChem3D(visible=0): """ launches Chem3D """ global c3dApp c3dApp = Dispatch('Chem3D.Application') if not c3dApp.Visible: c3dApp.Visible = visible def CloseChem3D(): """ shuts down Chem3D """ global c3dApp c3dApp.Quit() c3dApp = None availChem3DProps = ('DipoleMoment','BendEnergy','Non14VDWEnergy','StericEnergy', 'StretchBendEnergy','StretchEnergy','TorsionEnergy','VDW14Energy') def Add3DCoordsToMol(data,format,props={}): """ adds 3D coordinates to the data passed in using Chem3D **Arguments** - data: the molecular data - format: the format of _data_. Should be something accepted by _CDXConvert_ - props: (optional) a dictionary used to return calculated properties """ global c3dApp if c3dApp is None: StartChem3D() if format != 'chemical/mdl-molfile': molData = CDXClean(data,format,'chemical/mdl-molfile') else: molData = data molFName = tempfile.mktemp('.mol') open(molFName,'wb+').write(molData) doc = c3dApp.Documents.Open(molFName) if not doc: print 'cannot open molecule' raise ValueError,'No Molecule' # set up the MM2 job job = Dispatch('Chem3D.MM2Job') job.Type=1 job.DisplayEveryIteration=0 job.RecordEveryIteration=0 # start the calculation... doc.MM2Compute(job) # and wait for it to finish while doc.ComputeStatus in [0x434f4d50,0x50454e44]: pass #outFName = tempfile.mktemp('.mol') # this is horrible, but apparently Chem3D gets pissy with tempfiles: outFName = os.getcwd()+'/to3d.mol' doc.SaveAs(outFName) # generate the properties for prop in availChem3DProps: props[prop] = eval('doc.%s'%prop) doc.Close(0) os.unlink(molFName) c3dData = open(outFName,'r').read() gone = 0 while not gone: try: os.unlink(outFName) except: time.sleep(.5) else: gone = 1 return c3dData def OptimizeSDFile(inFileName,outFileName,problemFileName='problems.sdf', restartEvery=20): """ optimizes the structure of every molecule in the input SD file **Arguments** - inFileName: name of the input SD file - outFileName: name of the output SD file - problemFileName: (optional) name of the SD file used to store molecules which fail during the optimization process - restartEvery: (optional) Chem3D will be shut down and restarted every _restartEvery_ molecules to try and keep core leaks under control """ inFile = open(inFileName,'r') outFile = open(outFileName,'w+') problemFile = None props = {} lines = [] nextLine = inFile.readline() skip = 0 nDone = 0 t1 = time.time() while nextLine != '': if nextLine.find('M END') != -1: lines.append(nextLine) molBlock = string.join(lines,'') try: newMolBlock = Add3DCoordsToMol(molBlock,'chemical/mdl-molfile',props=props) except: badBlock = molBlock skip = 1 lines = [] else: skip = 0 lines = [newMolBlock] elif nextLine.find('$$$$') != -1: t2 = time.time() nDone += 1 print 'finished molecule %d in %f seconds'%(nDone,time.time()-t1) t1 = time.time() if nDone%restartEvery == 0: CloseChem3D() StartChem3D() outFile.close() outFile = open(outFileName,'a') if not skip: for prop in props.keys(): lines.append('> <%s>\n%f\n\n'%(prop,props[prop])) lines.append(nextLine) outFile.write(string.join(lines,'')) lines = [] else: skip = 0 lines.append(nextLine) if problemFile is None: problemFile = open(problemFileName,'w+') problemFile.write(badBlock) problemFile.write(string.join(lines,'')) lines = [] else: lines.append(nextLine) nextLine = inFile.readline() outFile.close() if problemFile is not None: problemFile.close() if __name__=='__main__': inStr = 'CCC(C=O)CCC' img = SmilesToPilImage(inStr) img.save('foo.jpg') convStr = CDXClean(inStr,'chemical/x-daylight-smiles','chemical/x-daylight-smiles') print 'in:',inStr print 'out:',convStr convStr = CDXConvert(inStr,'chemical/x-daylight-smiles','chemical/x-mdl-molfile') print 'in:',inStr print 'out:',convStr convStr2 = CDXClean(convStr,'chemical/x-mdl-molfile','chemical/x-mdl-molfile') print 'out2:',convStr2 inStr = 'COc1ccc(c2onc(c2C(=O)NCCc3ccc(F)cc3)c4ccc(F)cc4)c(OC)c1' convStr = CDXConvert(inStr,'chemical/x-daylight-smiles','chemical/x-mdl-molfile') out = open('test.mol','w+') out.write(convStr) out.close()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/utils/chemdraw.py", "copies": "2", "size": "11604", "license": "bsd-3-clause", "hash": -1931042545943586300, "line_mean": 26.2394366197, "line_max": 102, "alpha_frac": 0.6533092037, "autogenerated": false, "ratio": 3.2678118839763446, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49211210876763445, "avg_score": null, "num_lines": null }
""" unit testing code for surface calculations FIX: add tests for LabuteASA """ from __future__ import print_function from rdkit import RDConfig import unittest, os from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import MolSurf import os.path def feq(n1, n2, tol=1e-4): return abs(n1 - n2) <= tol class TestCase(unittest.TestCase): def setUp(self): if doLong: print('\n%s: ' % self.shortDescription(), end='') def testTPSAShort(self): " Short TPSA test " inName = RDConfig.RDDataDir + '/NCI/first_200.tpsa.csv' with open(inName, 'r') as inF: lines = inF.readlines() for line in lines: if line[0] != '#': line.strip() smi, ans = line.split(',') ans = float(ans) mol = Chem.MolFromSmiles(smi) calc = MolSurf.TPSA(mol) assert feq(calc, ans), 'bad TPSA for SMILES %s (%.2f != %.2f)' % (smi, calc, ans) def _testTPSALong(self): " Longer TPSA test " #inName = RDConfig.RDDataDir+'/NCI/first_5k.tpsa.csv' inName = os.path.join(RDConfig.RDCodeDir, 'Chem', 'test_data', 'NCI_5K_TPSA.csv') with open(inName, 'r') as inF: lines = inF.readlines() lineNo = 0 for line in lines: lineNo += 1 if line[0] != '#': line.strip() smi, ans = line.split(',') ans = float(ans) mol = Chem.MolFromSmiles(smi) if not mol: raise AssertionError('molecule construction failed on line %d' % lineNo) else: ok = 1 try: calc = MolSurf.TPSA(mol) except Exception: ok = 0 assert ok, 'Line %d: TPSA Calculation failed for SMILES %s' % (lineNo, smi) assert feq(calc, ans), 'Line %d: bad TPSA for SMILES %s (%.2f != %.2f)' % (lineNo, smi, calc, ans) def testHsAndTPSA(self): """ testing the impact of Hs in the graph on PSA calculations This was sf.net issue 1969745 """ mol = Chem.MolFromSmiles('c1c[nH]cc1') molH = Chem.AddHs(mol) psa = MolSurf.TPSA(mol) psaH = MolSurf.TPSA(molH) if (psa != psaH): psac = MolSurf.rdMolDescriptors._CalcTPSAContribs(mol) psaHc = MolSurf.rdMolDescriptors._CalcTPSAContribs(molH) for i, v in enumerate(psac): print('\t', i, '\t', v, '\t', psaHc[i]) while i < len(psaHc): print('\t\t\t', psaHc[i]) i += 1 self.assertEqual(psa, psaH) inName = RDConfig.RDDataDir + '/NCI/first_200.tpsa.csv' with open(inName, 'r') as inF: lines = inF.readlines() for line in lines: if line[0] != '#': line.strip() smi, ans = line.split(',') ans = float(ans) mol = Chem.MolFromSmiles(smi) mol = Chem.AddHs(mol) calc = MolSurf.TPSA(mol) self.assertTrue(feq(calc, ans), 'bad TPSA for SMILES %s (%.2f != %.2f)' % (smi, calc, ans)) if doLong: inName = os.path.join(RDConfig.RDCodeDir, 'Chem', 'test_data', 'NCI_5K_TPSA.csv') with open(inName, 'r') as inF: lines = inF.readlines() for line in lines: if line[0] != '#': line.strip() smi, ans = line.split(',') ans = float(ans) mol = Chem.MolFromSmiles(smi) mol = Chem.AddHs(mol) calc = MolSurf.TPSA(mol) self.assertTrue( feq(calc, ans), 'bad TPSA for SMILES %s (%.2f != %.2f)' % (smi, calc, ans)) 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/UnitTestSurf.py", "copies": "1", "size": "4259", "license": "bsd-3-clause", "hash": -8525855581562437000, "line_mean": 29.4214285714, "line_max": 99, "alpha_frac": 0.5632777647, "autogenerated": false, "ratio": 2.990870786516854, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4054148551216854, "avg_score": null, "num_lines": null }
"""unit testing code for the Crippen clogp and MR calculators """ from __future__ import print_function from rdkit import RDConfig import unittest,sys,os from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import Crippen def feq(n1,n2,tol=1e-5): return abs(n1-n2)<=tol class TestCase(unittest.TestCase): def setUp(self): self.fName = os.path.join(RDConfig.RDCodeDir,'Chem/test_data','aromat_regress.txt') self.fName2 = os.path.join(RDConfig.RDCodeDir,'Chem/test_data','NCI_aromat_regress.txt') def _readData(self,fName): d = [] lineNo=0 for line in open(fName,'r').xreadlines(): lineNo+=1 if len(line) and line[0] != '#': splitL = line.split('\t') if len(splitL)==4: smi1,smi2,count,ats = splitL d.append((lineNo,smi1,smi2,int(count),eval(ats))) self.data = d def test1(self,maxFailures=50): self._readData(self.fName) nMols = len(self.data) nFailed = 0 for i in range(nMols): lineNo,smi,smi2,tgtCount,tgtAts = self.data[i] try: mol = Chem.MolFromSmiles(smi) if not mol: raise ValueError except: mol = None print('failure(%d): '%lineNo,smi) print('-----------------------------') else: count = 0 aroms = [] for at in mol.GetAtoms(): if at.GetIsAromatic(): aroms.append(at.GetIdx()) count+=1 if count != tgtCount: print('Fail(%d): %s, %s'%(lineNo,smi,Chem.MolToSmiles(mol))) print('\t %d != %d'%(count,tgtCount)) print('\t ',repr(aroms)) print('\t ',repr(tgtAts)) print('-----------------------------') nFailed += 1 if nFailed >= maxFailures: assert 0 def test2(self,maxFailures=50): self._readData(self.fName2) nMols = len(self.data) nFailed = 0 for i in range(nMols): lineNo,smi,smi2,tgtCount,tgtAts = self.data[i] try: mol = Chem.MolFromSmiles(smi) if not mol: raise ValueError except: mol = None print('failure(%d): '%lineNo,smi) print('-----------------------------') else: count = 0 aroms = [] for at in mol.GetAtoms(): if at.GetIsAromatic(): aroms.append(at.GetIdx()) count+=1 if count != tgtCount: print('Fail(%d): %s, %s'%(lineNo,smi,Chem.MolToSmiles(mol))) print('\t %d != %d'%(count,tgtCount)) print('\t ',repr(aroms)) print('\t ',repr(tgtAts)) print('-----------------------------') nFailed += 1 if nFailed >= maxFailures: assert 0 if __name__ == '__main__': unittest.main()
{ "repo_name": "strets123/rdkit", "path": "rdkit/Chem/UnitTestArom.py", "copies": "3", "size": "3129", "license": "bsd-3-clause", "hash": -156726008307118560, "line_mean": 26.6902654867, "line_max": 92, "alpha_frac": 0.5343560243, "autogenerated": false, "ratio": 3.245850622406639, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5280206646706639, "avg_score": null, "num_lines": null }
"""unit testing code for the Crippen clogp and MR calculators """ from __future__ import print_function from rdkit import RDConfig import unittest, sys, os from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import Crippen def feq(n1, n2, tol=1e-5): return abs(n1 - n2) <= tol class TestCase(unittest.TestCase): def setUp(self): self.fName = os.path.join(RDConfig.RDCodeDir, 'Chem/test_data', 'aromat_regress.txt') self.fName2 = os.path.join(RDConfig.RDCodeDir, 'Chem/test_data', 'NCI_aromat_regress.txt') def _readData(self, fName): d = [] lineNo = 0 for line in open(fName, 'r').xreadlines(): lineNo += 1 if len(line) and line[0] != '#': splitL = line.split('\t') if len(splitL) == 4: smi1, smi2, count, ats = splitL d.append((lineNo, smi1, smi2, int(count), eval(ats))) self.data = d def test1(self, maxFailures=50): self._readData(self.fName) nMols = len(self.data) nFailed = 0 for i in range(nMols): lineNo, smi, smi2, tgtCount, tgtAts = self.data[i] mol = Chem.MolFromSmiles(smi) if mol is None: print('failure(%d): ' % lineNo, smi) print('-----------------------------') else: count = 0 aroms = [] for at in mol.GetAtoms(): if at.GetIsAromatic(): aroms.append(at.GetIdx()) count += 1 if count != tgtCount: print('Fail(%d): %s, %s' % (lineNo, smi, Chem.MolToSmiles(mol))) print('\t %d != %d' % (count, tgtCount)) print('\t ', repr(aroms)) print('\t ', repr(tgtAts)) print('-----------------------------') nFailed += 1 if nFailed >= maxFailures: assert 0 def test2(self, maxFailures=50): self._readData(self.fName2) nMols = len(self.data) nFailed = 0 for i in range(nMols): lineNo, smi, smi2, tgtCount, tgtAts = self.data[i] mol = Chem.MolFromSmiles(smi) if mol is None: print('failure(%d): ' % lineNo, smi) print('-----------------------------') else: count = 0 aroms = [] for at in mol.GetAtoms(): if at.GetIsAromatic(): aroms.append(at.GetIdx()) count += 1 if count != tgtCount: print('Fail(%d): %s, %s' % (lineNo, smi, Chem.MolToSmiles(mol))) print('\t %d != %d' % (count, tgtCount)) print('\t ', repr(aroms)) print('\t ', repr(tgtAts)) print('-----------------------------') nFailed += 1 if nFailed >= maxFailures: assert 0 if __name__ == '__main__': unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/UnitTestArom.py", "copies": "1", "size": "3001", "license": "bsd-3-clause", "hash": -2269021845948288800, "line_mean": 29.01, "line_max": 94, "alpha_frac": 0.5384871709, "autogenerated": false, "ratio": 3.1589473684210527, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9138356610650218, "avg_score": 0.01181558573416696, "num_lines": 100 }
"""unit testing code for the database utilities """ from rdkit import RDConfig import unittest, os, tempfile from rdkit.Dbase import DbUtils from rdkit.Dbase.DbConnection import DbConnect class TestCase(unittest.TestCase): def setUp(self): #print '\n%s: '%self.shortDescription(), self.baseDir = os.path.join(RDConfig.RDCodeDir, 'Dbase', 'test_data') self.dbName = RDConfig.RDTestDatabase if RDConfig.useSqlLite: tmpf, tempName = tempfile.mkstemp(suffix='sqlt') self.tempDbName = tempName else: self.tempDbName = '::RDTests' self.colHeads = ('int_col', 'floatCol', 'strCol') self.colTypes = ('integer', 'float', 'string') def tearDown(self): if RDConfig.useSqlLite and os.path.exists(self.tempDbName): try: os.unlink(self.tempDbName) except: import traceback traceback.print_exc() def _confirm(self, tblName, dbName=None): if dbName is None: dbName = self.dbName conn = DbConnect(dbName, tblName) res = conn.GetColumnNamesAndTypes() assert len(res) == len(self.colHeads), 'bad number of columns' names = [x[0] for x in res] for i in range(len(names)): assert names[i].upper() == self.colHeads[i].upper(), 'bad column head' if RDConfig.useSqlLite: # doesn't seem to be any column type info available return types = [x[1] for x in res] for i in range(len(types)): assert types[i] == self.colTypes[i], 'bad column type' def test1Txt(self): """ test reading from a text file """ with open(os.path.join(self.baseDir, 'dbtest.csv'), 'r') as inF: tblName = 'fromtext' DbUtils.TextFileToDatabase(self.tempDbName, tblName, inF) self._confirm(tblName, dbName=self.tempDbName) def test3Txt(self): """ test reading from a text file including null markers""" with open(os.path.join(self.baseDir, 'dbtest.nulls.csv'), 'r') as inF: tblName = 'fromtext2' DbUtils.TextFileToDatabase(self.tempDbName, tblName, inF, nullMarker='NA') self._confirm(tblName, dbName=self.tempDbName) def testGetData1(self): """ basic functionality """ d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=1) assert len(d) == 10 assert tuple(d[0]) == (0, 11) assert tuple(d[2]) == (4, 31) with self.assertRaisesRegexp(IndexError, ""): d[11] def testGetData2(self): """ using a RandomAccessDbResultSet """ d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=0, randomAccess=1) assert tuple(d[0]) == (0, 11) assert tuple(d[2]) == (4, 31) assert len(d) == 10 with self.assertRaisesRegexp(IndexError, ""): d[11] def testGetData3(self): """ using a DbResultSet """ d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=0, randomAccess=0) with self.assertRaisesRegexp(TypeError, ""): len(d) rs = [] for thing in d: rs.append(thing) assert len(rs) == 10 assert tuple(rs[0]) == (0, 11) assert tuple(rs[2]) == (4, 31) def testGetData4(self): """ using a RandomAccessDbResultSet with a Transform """ fn = lambda x: (x[0], x[1] * 2) d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=0, randomAccess=1, transform=fn) assert tuple(d[0]) == (0, 22) assert tuple(d[2]) == (4, 62) assert len(d) == 10 with self.assertRaisesRegexp(IndexError, ""): d[11] def testGetData5(self): """ using a DbResultSet with a Transform """ fn = lambda x: (x[0], x[1] * 2) d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=0, randomAccess=0, transform=fn) with self.assertRaisesRegexp(TypeError, ""): len(d) rs = [] for thing in d: rs.append(thing) assert len(rs) == 10 assert tuple(rs[0]) == (0, 22) assert tuple(rs[2]) == (4, 62) if __name__ == '__main__': unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Dbase/UnitTestDbUtils.py", "copies": "1", "size": "4183", "license": "bsd-3-clause", "hash": -6682755154841806000, "line_mean": 30.4511278195, "line_max": 95, "alpha_frac": 0.635190055, "autogenerated": false, "ratio": 3.2176923076923076, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43528823626923074, "avg_score": null, "num_lines": null }
"""unit testing code for the database utilities """ import os import tempfile import unittest from six import StringIO from rdkit import RDConfig from rdkit.Dbase import DbUtils from rdkit.Dbase.DbConnection import DbConnect try: from contextlib import redirect_stdout except: from rdkit.TestRunner import redirect_stdout class TestCase(unittest.TestCase): def setUp(self): self.baseDir = os.path.join(RDConfig.RDCodeDir, 'Dbase', 'test_data') self.dbName = RDConfig.RDTestDatabase if RDConfig.useSqlLite: _, tempName = tempfile.mkstemp(suffix='sqlt') self.tempDbName = tempName else: self.tempDbName = '::RDTests' self.colHeads = ('int_col', 'floatCol', 'strCol') self.colTypes = ('integer', 'float', 'string') def tearDown(self): if RDConfig.useSqlLite and os.path.exists(self.tempDbName): try: os.unlink(self.tempDbName) except: import traceback traceback.print_exc() def _confirm(self, tblName, dbName=None, colHeads=None, colTypes=None): dbName = dbName or self.dbName colHeads = colHeads or self.colHeads colTypes = colTypes or self.colTypes conn = DbConnect(dbName, tblName) res = conn.GetColumnNamesAndTypes() assert len(res) == len(colHeads), 'bad number of columns' names = [x[0] for x in res] for i in range(len(names)): assert names[i].upper() == colHeads[i].upper(), 'bad column head' if RDConfig.useSqlLite: # doesn't seem to be any column type info available return types = [x[1] for x in res] for i in range(len(types)): assert types[i] == colTypes[i], 'bad column type' def test1Txt(self): """ test reading from a text file """ with open(os.path.join(self.baseDir, 'dbtest.csv'), 'r') as inF: tblName = 'fromtext' f = StringIO() with redirect_stdout(f): DbUtils.TextFileToDatabase(self.tempDbName, tblName, inF) self._confirm(tblName, dbName=self.tempDbName) def test3Txt(self): """ test reading from a text file including null markers""" with open(os.path.join(self.baseDir, 'dbtest.nulls.csv'), 'r') as inF: tblName = 'fromtext2' f = StringIO() with redirect_stdout(f): DbUtils.TextFileToDatabase(self.tempDbName, tblName, inF, nullMarker='NA') self._confirm(tblName, dbName=self.tempDbName) def testGetData1(self): """ basic functionality """ d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=1) assert len(d) == 10 assert tuple(d[0]) == (0, 11) assert tuple(d[2]) == (4, 31) with self.assertRaisesRegexp(IndexError, ""): d[11] def testGetData2(self): """ using a RandomAccessDbResultSet """ d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=0, randomAccess=1) assert tuple(d[0]) == (0, 11) assert tuple(d[2]) == (4, 31) assert len(d) == 10 with self.assertRaisesRegexp(IndexError, ""): d[11] def testGetData3(self): """ using a DbResultSet """ d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=0, randomAccess=0) with self.assertRaisesRegexp(TypeError, ""): len(d) rs = [] for thing in d: rs.append(thing) assert len(rs) == 10 assert tuple(rs[0]) == (0, 11) assert tuple(rs[2]) == (4, 31) def testGetData4(self): """ using a RandomAccessDbResultSet with a Transform """ def fn(x): return (x[0], x[1] * 2) d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=0, randomAccess=1, transform=fn) assert tuple(d[0]) == (0, 22) assert tuple(d[2]) == (4, 62) assert len(d) == 10 with self.assertRaisesRegexp(IndexError, ""): d[11] def testGetData5(self): """ using a DbResultSet with a Transform """ def fn(x): return (x[0], x[1] * 2) d = DbUtils.GetData(self.dbName, 'ten_elements', forceList=0, randomAccess=0, transform=fn) with self.assertRaisesRegexp(TypeError, ""): len(d) rs = [] for thing in d: rs.append(thing) assert len(rs) == 10 assert tuple(rs[0]) == (0, 22) assert tuple(rs[2]) == (4, 62) def test_take(self): self.assertEqual(list(DbUtils._take([1, 2, 3, 4], [2, 3])), [3, 4]) self.assertEqual(list(DbUtils._take([1, 2, 3, 4], [0, 3])), [1, 4]) def test_GetColumns(self): d = DbUtils.GetColumns(self.dbName, 'ten_elements', 'val') self.assertEqual(len(d), 10) def test_GetData_where(self): d = DbUtils.GetData(self.dbName, 'ten_elements_dups', forceList=0, randomAccess=0, whereString='id<4') self.assertEqual(len(list(d)), 4) self.assertTrue(all(x[0] < 4 for x in d)) d = DbUtils.GetData(self.dbName, 'ten_elements_dups', forceList=0, randomAccess=0, whereString='id<10') self.assertEqual(len(list(d)), 10) self.assertTrue(all(x[0] < 10 for x in d)) d = DbUtils.GetData(self.dbName, 'ten_elements_dups', removeDups=1, forceList=True) self.assertEqual(len(list(d)), 10) def test_DatabaseToText(self): txt = DbUtils.DatabaseToText(self.dbName, 'ten_elements') self.assertIn('id,val', txt) self.assertIn('0,11', txt) self.assertIn('18,101', txt) self.assertEqual(len(txt.split('\n')), 11) txt = DbUtils.DatabaseToText(self.dbName, 'ten_elements', fields='val') self.assertNotIn('id', txt) self.assertNotIn(',', txt) txt = DbUtils.DatabaseToText(self.dbName, 'ten_elements', where='id<4') self.assertIn('id,val', txt) self.assertEqual(len(txt.split('\n')), 3) def test_TypeFinder(self): data = [('-', 1.45, 'abc', None), (20, 3, 'defgh', None)] self.assertEqual( DbUtils.TypeFinder(data, 2, 4, nullMarker='-'), [[int, 2], [float, 4], [str, 5], [-1, 1]]) def test_AdjustColHeadings(self): headers = ['abc def', ' abc def', 'abc-def ', 'abc.def'] self.assertEqual(DbUtils._AdjustColHeadings(headers, 7), ['abc_def'] * 4) f = StringIO() with redirect_stdout(f): headers = ['abc def', ' abc def', 'abc-def ', 'abc.def'] self.assertEqual(DbUtils._AdjustColHeadings(headers, 3), ['abc'] * 4) self.assertIn('Heading', f.getvalue()) def test_GetTypeStrings(self): headers = ['pk', 'a', 'b', 'c'] colTypes = [(int, 2), (int, 3), (float, 5), (str, 10)] self.assertEqual( DbUtils.GetTypeStrings(headers, colTypes), ['pk integer', 'a integer', 'b double precision', 'c varchar(10)']) self.assertEqual( DbUtils.GetTypeStrings(headers, colTypes, keyCol='pk'), ['pk integer not null primary key', 'a integer', 'b double precision', 'c varchar(10)']) def test_DatabaseToDatabase(self): tblName = 'db2db' f = StringIO() with redirect_stdout(f): DbUtils.DatabaseToDatabase(self.dbName, 'ten_elements', self.tempDbName, tblName) self._confirm(tblName, dbName=self.tempDbName, colHeads=['id', 'val']) if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Dbase/UnitTestDbUtils.py", "copies": "1", "size": "7275", "license": "bsd-3-clause", "hash": 8602061904287650000, "line_mean": 31.6233183857, "line_max": 96, "alpha_frac": 0.6328522337, "autogenerated": false, "ratio": 3.200615926088869, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4333468159788869, "avg_score": null, "num_lines": null }
"""unit testing code for the EState fingerprinting validation values are from the paper (JCICS _35_ 1039-1045 (1995)) """ from __future__ import print_function import unittest import numpy from rdkit import Chem from rdkit.Chem import EState from rdkit.Chem.EState import Fingerprinter class TestCase(unittest.TestCase): def setUp(self): pass def _validate(self,vals,tol=1e-2,show=0): for smi,c,v in vals: mol = Chem.MolFromSmiles(smi) counts,vals = Fingerprinter.FingerprintMol(mol) counts = counts[numpy.nonzero(counts)] vals = vals[numpy.nonzero(vals)] if show: print(counts) print(vals) assert len(c)==len(counts),'bad count len for smiles: %s'%(smi) assert len(v)==len(vals),'bad val len for smiles: %s'%(smi) c = numpy.array(c) assert max(abs(c-counts))<tol,'bad count for SMILES: %s'%(smi) v = numpy.array(v) assert max(abs(v-vals))<tol,'bad val for SMILES: %s'%(smi) def test1(self): """ molecules """ data = [ ('c1[nH]cnc1CC(N)C(O)=O',[1,2,1,1,1,1,1,1,1,1], [0.26,3.12,-0.86,-1.01,0.67,5.25,2.71,3.84,8.42,10.26]), ('NCCc1ccc(O)c(O)c1',[2,3,3,1,2], [1.26,4.71,0.75,5.30,17.97]), ] self._validate(data,show=0) if __name__ == '__main__': unittest.main()
{ "repo_name": "soerendip42/rdkit", "path": "rdkit/Chem/EState/UnitTestFingerprints.py", "copies": "4", "size": "1628", "license": "bsd-3-clause", "hash": -6992751113901026000, "line_mean": 27.5614035088, "line_max": 69, "alpha_frac": 0.6222358722, "autogenerated": false, "ratio": 2.759322033898305, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5381557906098305, "avg_score": null, "num_lines": null }
"""unit testing code for the EState indices validation values are from the paper (JCICS _31_ 76-81 (1991)) """ from __future__ import print_function import unittest import numpy from rdkit import Chem from rdkit.Chem import EState class TestCase(unittest.TestCase): def setUp(self): #print '\n%s: '%self.shortDescription(), pass def _validate(self,vals,tol=1e-2,show=0): for smi,ans in vals: mol = Chem.MolFromSmiles(smi) ans = numpy.array(ans) inds = EState.EStateIndices(mol) maxV = max(abs(ans-inds)) if show: print(inds) assert maxV<tol,'bad EStates for smiles: %s'%(smi) def test1(self): """ simple molecules """ data = [ ('CCCC',[2.18,1.32,1.32,2.18]), ('CCCCC',[2.21,1.34,1.39,1.34,2.21]), ('CCCCCCC',[2.24,1.36,1.42,1.44,1.42,1.36,2.24]), ('CCCCCCCCCC',[2.27,1.37,1.44,1.46,1.47,1.47,1.46,1.44,1.37,2.27]), ] self._validate(data) def test2(self): """ isomers """ data = [ ('CCCCCC',[2.23,1.36,1.41,1.41,1.36,2.23]), ('CCC(C)CC',[2.23,1.33,0.94,2.28,1.33,2.23]), ('CC(C)CCC',[2.25,0.90,2.25,1.38,1.33,2.22]), ('CC(C)(C)CC',[2.24,0.54,2.24,2.24,1.27,2.20]), ] self._validate(data) def test3(self): """ heteroatoms """ data = [ ('CCCCOCCCC',[2.18,1.24,1.21,0.95,5.31,0.95,1.21,1.24,2.18]), ('CCC(C)OC(C)CC',[2.15,1.12,0.43,2.12,5.54,0.43,2.12,1.12,2.15]), ('CC(C)(C)OC(C)(C)C',[2.07,-0.02,2.07,2.07,5.63,-0.02,2.07,2.07,2.07]), ('CC(C)CC',[2.22,0.88,2.22,1.31,2.20]), ('CC(C)CN',[2.10,0.66,2.10,0.81,5.17]), ('CC(C)CO',[1.97,0.44,1.97,0.31,8.14]), ('CC(C)CF',[1.85,0.22,1.85,-0.19,11.11]), ('CC(C)CCl',[2.09,0.65,2.09,0.78,5.34]), ('CC(C)CBr',[2.17,0.80,2.17,1.11,3.31]), ('CC(C)CI',[2.21,0.87,2.21,1.28,2.38]), ] self._validate(data,show=0) def test4(self): """ more heteroatoms """ data = [ ('CC(N)C(=O)O',[1.42,-0.73,4.84,-0.96,9.57,7.86]), ('CCOCC',[1.99,0.84,4.83,0.84,1.99]), ('CCSCC',[2.17,1.26,1.96,1.26,2.17]), #NOTE: this does not match the values in the paper ('CC(=O)OC',[1.36,-0.24,9.59,4.11,1.35]), ('CC(=S)OC',[1.73,0.59,4.47,4.48,1.56]), ] self._validate(data,show=0) def test5(self): """ aromatics with heteroatoms """ data = [ ('Fc1ccc(C)cc1',[12.09,-0.17,1.45,1.75,1.09,1.93,1.75,1.45]), ('Clc1ccc(C)cc1',[5.61,0.80,1.89,1.99,1.24,2.04,1.99,1.89]), ('Brc1ccc(C)cc1',[3.35,1.14,2.04,2.07,1.30,2.08,2.07,2.04]), ('Ic1ccc(C)cc1',[2.30,1.30,2.10,2.11,1.32,2.09,2.11,2.10]), ] self._validate(data,show=0) if __name__ == '__main__': unittest.main()
{ "repo_name": "soerendip42/rdkit", "path": "rdkit/Chem/EState/UnitTestEState.py", "copies": "4", "size": "3044", "license": "bsd-3-clause", "hash": -4891856366484477000, "line_mean": 28.8431372549, "line_max": 95, "alpha_frac": 0.5384362681, "autogenerated": false, "ratio": 2.1742857142857144, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47127219823857147, "avg_score": null, "num_lines": null }
"""unit testing code for the EState indices validation values are from the paper (JCICS _31_ 76-81 (1991)) """ from __future__ import print_function import unittest from six import StringIO import numpy as np from rdkit import Chem from rdkit.Chem import EState class TestCase(unittest.TestCase): def _compareEstates(self, val1, val2, msg, tol=1e-2): maxV = max(abs(val1 - val2)) self.assertLess(maxV, tol, msg) def _validate(self, vals, places=2, tol=1e-2, debug=False): for smi, ans in vals: ans = np.array(ans) mol = Chem.MolFromSmiles(smi) inds = EState.EStateIndices(mol) if debug: # pragma: nocover print(inds) self._compareEstates(ans, inds, 'bad EStates for smiles: {0}'.format(smi), tol=tol) self.assertLess(abs(EState.MaxEStateIndex(mol) - max(ans)), tol) self.assertLess(abs(EState.MinEStateIndex(mol) - min(ans)), tol) self.assertLess(abs(EState.MaxAbsEStateIndex(mol) - max(abs(ans))), tol) self.assertLess(abs(EState.MinAbsEStateIndex(mol) - min(abs(ans))), tol) def test_simpleMolecules(self): data = [ ('CCCC', [2.18, 1.32, 1.32, 2.18]), ('CCCCC', [2.21, 1.34, 1.39, 1.34, 2.21]), ('CCCCCCC', [2.24, 1.36, 1.42, 1.44, 1.42, 1.36, 2.24]), ('CCCCCCCCCC', [2.27, 1.37, 1.44, 1.46, 1.47, 1.47, 1.46, 1.44, 1.37, 2.27]), ] self._validate(data) def test_isomers(self): data = [ ('CCCCCC', [2.23, 1.36, 1.41, 1.41, 1.36, 2.23]), ('CCC(C)CC', [2.23, 1.33, 0.94, 2.28, 1.33, 2.23]), ('CC(C)CCC', [2.25, 0.90, 2.25, 1.38, 1.33, 2.22]), ('CC(C)(C)CC', [2.24, 0.54, 2.24, 2.24, 1.27, 2.20]), ] self._validate(data) def test_heteroatoms1(self): data = [ ('CCCCOCCCC', [2.18, 1.24, 1.21, 0.95, 5.31, 0.95, 1.21, 1.24, 2.18]), ('CCC(C)OC(C)CC', [2.15, 1.12, 0.43, 2.12, 5.54, 0.43, 2.12, 1.12, 2.15]), ('CC(C)(C)OC(C)(C)C', [2.07, -0.02, 2.07, 2.07, 5.63, -0.02, 2.07, 2.07, 2.07]), ('CC(C)CC', [2.22, 0.88, 2.22, 1.31, 2.20]), ('CC(C)CN', [2.10, 0.66, 2.10, 0.81, 5.17]), ('CC(C)CO', [1.97, 0.44, 1.97, 0.31, 8.14]), ('CC(C)CF', [1.85, 0.22, 1.85, -0.19, 11.11]), ('CC(C)CCl', [2.09, 0.65, 2.09, 0.78, 5.34]), ('CC(C)CBr', [2.17, 0.80, 2.17, 1.11, 3.31]), ('CC(C)CI', [2.21, 0.87, 2.21, 1.28, 2.38]), ] self._validate(data, debug=False) def test_heteroatoms2(self): data = [ ('CC(N)C(=O)O', [1.42, -0.73, 4.84, -0.96, 9.57, 7.86]), ('CCOCC', [1.99, 0.84, 4.83, 0.84, 1.99]), ('CCSCC', [2.17, 1.26, 1.96, 1.26, 2.17]), # NOTE: this doesn't match the values in the paper ('CC(=O)OC', [1.36, -0.24, 9.59, 4.11, 1.35]), ('CC(=S)OC', [1.73, 0.59, 4.47, 4.48, 1.56]), ] self._validate(data, debug=False) def test_aromatics(self): # aromatics with heteroatoms data = [ ('Fc1ccc(C)cc1', [12.09, -0.17, 1.45, 1.75, 1.09, 1.93, 1.75, 1.45]), ('Clc1ccc(C)cc1', [5.61, 0.80, 1.89, 1.99, 1.24, 2.04, 1.99, 1.89]), ('Brc1ccc(C)cc1', [3.35, 1.14, 2.04, 2.07, 1.30, 2.08, 2.07, 2.04]), ('Ic1ccc(C)cc1', [2.30, 1.30, 2.10, 2.11, 1.32, 2.09, 2.11, 2.10]), ] self._validate(data, debug=False) def test_GetPrincipleQuantumNumber(self): for principalQN, (nmin, nmax) in enumerate( [(1, 2), (3, 10), (11, 18), (19, 36), (37, 54), (55, 86), (87, 120)], 1): for n in range(nmin, nmax + 1): self.assertEqual(EState.GetPrincipleQuantumNumber(n), principalQN) def test_cacheEstate(self): mol = Chem.MolFromSmiles('CCCC') expected = [2.18, 1.32, 1.32, 2.18] # The mol object has no information about E-states self.assertFalse(hasattr(mol, '_eStateIndices')) inds = EState.EStateIndices(mol) self._compareEstates(inds, expected, 'cacheTest') # We now have E-states stored with the molecule self.assertTrue(hasattr(mol, '_eStateIndices')) # Let's make sure that we skip the calculation next time if force is False mol._eStateIndices = 'cached' self.assertTrue(hasattr(mol, '_eStateIndices')) inds = EState.EStateIndices(mol, force=False) self.assertEqual(inds, 'cached') # But with force (default) we calculate again inds = EState.EStateIndices(mol) self._compareEstates(inds, expected, 'cacheTest') self._compareEstates(mol._eStateIndices, expected, 'cacheTest') def test_exampleCode(self): # We make sure that the example code runs from rdkit.TestRunner import redirect_stdout f = StringIO() with redirect_stdout(f): EState.EState._exampleCode() s = f.getvalue() self.assertIn('CC(N)C(=O)O', s) if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/EState/UnitTestEState.py", "copies": "1", "size": "5001", "license": "bsd-3-clause", "hash": 3484069669075651600, "line_mean": 34.4680851064, "line_max": 100, "alpha_frac": 0.5852829434, "autogenerated": false, "ratio": 2.468410661401777, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3553693604801777, "avg_score": null, "num_lines": null }
"""unit testing code for the signatures """ from __future__ import print_function import unittest import os from rdkit.six import next from rdkit import RDConfig from rdkit import Chem from rdkit.Chem.Pharm2D import Gobbi_Pharm2D,Generate class TestCase(unittest.TestCase): def setUp(self): self.factory = Gobbi_Pharm2D.factory def test1Sigs(self): probes = [ ('OCCC=O',{'HA':(1,((0,),(4,))), 'HD':(1,((0,),)), 'LH':(0,None), 'AR':(0,None), 'RR':(0,None), 'X':(0,None), 'BG':(0,None), 'AG':(0,None), } ), ('OCCC(=O)O',{'HA':(1,((0,),(4,))), 'HD':(1,((0,),(5,))), 'LH':(0,None), 'AR':(0,None), 'RR':(0,None), 'X':(0,None), 'BG':(0,None), 'AG':(1,((3,),)), } ), ('CCCN',{'HA':(1,((3,),)), 'HD':(1,((3,),)), 'LH':(0,None), 'AR':(0,None), 'RR':(0,None), 'X':(0,None), 'BG':(1,((3,),)), 'AG':(0,None), } ), ('CCCCC',{'HA':(0,None), 'HD':(0,None), 'LH':(1,((1,),(3,))), 'AR':(0,None), 'RR':(0,None), 'X':(0,None), 'BG':(0,None), 'AG':(0,None), } ), ('CC1CCC1',{'HA':(0,None), 'HD':(0,None), 'LH':(1,((1,),(3,))), 'AR':(0,None), 'RR':(1,((1,),)), 'X':(0,None), 'BG':(0,None), 'AG':(0,None), } ), ('[SiH3]C1CCC1',{'HA':(0,None), 'HD':(0,None), 'LH':(1,((1,),)), 'AR':(0,None), 'RR':(1,((1,),)), 'X':(1,((0,),)), 'BG':(0,None), 'AG':(0,None), } ), ('[SiH3]c1ccccc1',{'HA':(0,None), 'HD':(0,None), 'LH':(0,None), 'AR':(1,((1,),)), 'RR':(0,None), 'X':(1,((0,),)), 'BG':(0,None), 'AG':(0,None), } ), ] for smi,d in probes: mol = Chem.MolFromSmiles(smi) feats=self.factory.featFactory.GetFeaturesForMol(mol) for k in d.keys(): shouldMatch,mapList=d[k] feats=self.factory.featFactory.GetFeaturesForMol(mol,includeOnly=k) if shouldMatch: self.assertTrue(feats) self.assertEqual(len(feats),len(mapList)) aids = [(x.GetAtomIds()[0],) for x in feats] aids.sort() self.assertEqual(tuple(aids),mapList) def test2Sigs(self): probes = [('O=CCC=O',(149,)), ('OCCC=O',(149,156)), ('OCCC(=O)O',(22, 29, 149, 154, 156, 184, 28822, 30134)), ] for smi,tgt in probes: sig = Generate.Gen2DFingerprint(Chem.MolFromSmiles(smi),self.factory) self.assertEqual(len(sig),39972) bs = tuple(sig.GetOnBits()) self.assertEqual(len(bs),len(tgt)) self.assertEqual(bs,tgt) def testOrderBug(self): sdFile = os.path.join(RDConfig.RDCodeDir,'Chem','Pharm2D','test_data','orderBug.sdf') suppl = Chem.SDMolSupplier(sdFile) m1 = next(suppl) m2 = next(suppl) sig1 = Generate.Gen2DFingerprint(m1,self.factory) sig2 = Generate.Gen2DFingerprint(m2,self.factory) ob1 = set(sig1.GetOnBits()) ob2 = set(sig2.GetOnBits()) self.assertEqual(sig1,sig2) def testOrderBug2(self): from rdkit.Chem import Randomize from rdkit import DataStructs probes = ['Oc1nc(Oc2ncccc2)ccc1'] for smi in probes: m1 = Chem.MolFromSmiles(smi) #m1.Debug() sig1 = Generate.Gen2DFingerprint(m1,self.factory) csmi = Chem.MolToSmiles(m1) m2 = Chem.MolFromSmiles(csmi) #m2.Debug() sig2 = Generate.Gen2DFingerprint(m2,self.factory) self.assertTrue(list(sig1.GetOnBits())==list(sig2.GetOnBits()),'%s %s'%(smi,csmi)) self.assertEqual(DataStructs.DiceSimilarity(sig1,sig2),1.0) self.assertEqual(sig1,sig2) for i in range(10): m2 = Randomize.RandomizeMol(m1) sig2 = Generate.Gen2DFingerprint(m2,self.factory) if sig2!=sig1: Generate._verbose=True print('----------------') sig1 = Generate.Gen2DFingerprint(m1,self.factory) print('----------------') sig2 = Generate.Gen2DFingerprint(m2,self.factory) print('----------------') print(Chem.MolToMolBlock(m1)) print('----------------') print(Chem.MolToMolBlock(m2)) print('----------------') s1 = set(sig1.GetOnBits()) s2= set(sig2.GetOnBits()) print(s1.difference(s2)) self.assertEqual(sig1,sig2) def testBitInfo(self): m = Chem.MolFromSmiles('OCC=CC(=O)O') bi = {} sig = Generate.Gen2DFingerprint(m,Gobbi_Pharm2D.factory,bitInfo=bi) self.assertEqual(sig.GetNumOnBits(),len(bi)) self.assertEqual(list(sig.GetOnBits()),sorted(bi.keys())) self.assertEqual(sorted(bi.keys()),[23, 30, 150, 154, 157, 185, 28878, 30184]) self.assertEqual(sorted(bi[28878]),[[(0,), (5,), (6,)]]) self.assertEqual(sorted(bi[157]),[[(0,), (6,)], [(5,), (0,)]]) if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/Pharm2D/UnitTestGobbi.py", "copies": "3", "size": "5982", "license": "bsd-3-clause", "hash": 5901374106605671000, "line_mean": 31.6885245902, "line_max": 89, "alpha_frac": 0.4622199933, "autogenerated": false, "ratio": 3.1401574803149606, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5102377473614961, "avg_score": null, "num_lines": null }
"""unit testing code for the signatures """ import unittest import os from rdkit import RDConfig from rdkit import Chem from rdkit.Chem.Pharm2D import Gobbi_Pharm2D,Generate class TestCase(unittest.TestCase): def setUp(self): self.factory = Gobbi_Pharm2D.factory def test1Sigs(self): probes = [ ('OCCC=O',{'HA':(1,((0,),(4,))), 'HD':(1,((0,),)), 'LH':(0,None), 'AR':(0,None), 'RR':(0,None), 'X':(0,None), 'BG':(0,None), 'AG':(0,None), } ), ('OCCC(=O)O',{'HA':(1,((0,),(4,))), 'HD':(1,((0,),(5,))), 'LH':(0,None), 'AR':(0,None), 'RR':(0,None), 'X':(0,None), 'BG':(0,None), 'AG':(1,((3,),)), } ), ('CCCN',{'HA':(1,((3,),)), 'HD':(1,((3,),)), 'LH':(0,None), 'AR':(0,None), 'RR':(0,None), 'X':(0,None), 'BG':(1,((3,),)), 'AG':(0,None), } ), ('CCCCC',{'HA':(0,None), 'HD':(0,None), 'LH':(1,((1,),(3,))), 'AR':(0,None), 'RR':(0,None), 'X':(0,None), 'BG':(0,None), 'AG':(0,None), } ), ('CC1CCC1',{'HA':(0,None), 'HD':(0,None), 'LH':(1,((1,),(3,))), 'AR':(0,None), 'RR':(1,((1,),)), 'X':(0,None), 'BG':(0,None), 'AG':(0,None), } ), ('[SiH3]C1CCC1',{'HA':(0,None), 'HD':(0,None), 'LH':(1,((1,),)), 'AR':(0,None), 'RR':(1,((1,),)), 'X':(1,((0,),)), 'BG':(0,None), 'AG':(0,None), } ), ('[SiH3]c1ccccc1',{'HA':(0,None), 'HD':(0,None), 'LH':(0,None), 'AR':(1,((1,),)), 'RR':(0,None), 'X':(1,((0,),)), 'BG':(0,None), 'AG':(0,None), } ), ] for smi,d in probes: mol = Chem.MolFromSmiles(smi) feats=self.factory.featFactory.GetFeaturesForMol(mol) for k in d.keys(): shouldMatch,mapList=d[k] feats=self.factory.featFactory.GetFeaturesForMol(mol,includeOnly=k) if shouldMatch: self.failUnless(feats) self.failUnlessEqual(len(feats),len(mapList)) aids = [(x.GetAtomIds()[0],) for x in feats] aids.sort() self.failUnlessEqual(tuple(aids),mapList) def test2Sigs(self): probes = [('O=CCC=O',(149,)), ('OCCC=O',(149,156)), ('OCCC(=O)O',(22, 29, 149, 154, 156, 184, 28822, 30134)), ] for smi,tgt in probes: sig = Generate.Gen2DFingerprint(Chem.MolFromSmiles(smi),self.factory) self.failUnlessEqual(len(sig),39972) bs = tuple(sig.GetOnBits()) self.failUnlessEqual(len(bs),len(tgt)) self.failUnlessEqual(bs,tgt) def testOrderBug(self): sdFile = os.path.join(RDConfig.RDCodeDir,'Chem','Pharm2D','test_data','orderBug.sdf') suppl = Chem.SDMolSupplier(sdFile) m1 =suppl.next() m2 = suppl.next() sig1 = Generate.Gen2DFingerprint(m1,self.factory) sig2 = Generate.Gen2DFingerprint(m2,self.factory) ob1 = set(sig1.GetOnBits()) ob2 = set(sig2.GetOnBits()) self.failUnlessEqual(sig1,sig2) def testOrderBug2(self): from rdkit.Chem import Randomize from rdkit import DataStructs probes = ['Oc1nc(Oc2ncccc2)ccc1'] for smi in probes: m1 = Chem.MolFromSmiles(smi) #m1.Debug() sig1 = Generate.Gen2DFingerprint(m1,self.factory) csmi = Chem.MolToSmiles(m1) m2 = Chem.MolFromSmiles(csmi) #m2.Debug() sig2 = Generate.Gen2DFingerprint(m2,self.factory) self.failUnless(list(sig1.GetOnBits())==list(sig2.GetOnBits()),'%s %s'%(smi,csmi)) self.failUnlessEqual(DataStructs.DiceSimilarity(sig1,sig2),1.0) self.failUnlessEqual(sig1,sig2) for i in range(10): m2 = Randomize.RandomizeMol(m1) sig2 = Generate.Gen2DFingerprint(m2,self.factory) if sig2!=sig1: Generate._verbose=True print '----------------' sig1 = Generate.Gen2DFingerprint(m1,self.factory) print '----------------' sig2 = Generate.Gen2DFingerprint(m2,self.factory) print '----------------' print Chem.MolToMolBlock(m1) print '----------------' print Chem.MolToMolBlock(m2) print '----------------' s1 = set(sig1.GetOnBits()) s2= set(sig2.GetOnBits()) print s1.difference(s2) self.failUnlessEqual(sig1,sig2) if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Pharm2D/UnitTestGobbi.py", "copies": "2", "size": "5463", "license": "bsd-3-clause", "hash": -6044508081593510000, "line_mean": 31.1352941176, "line_max": 89, "alpha_frac": 0.449752883, "autogenerated": false, "ratio": 3.2003514938488578, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4650104376848857, "avg_score": null, "num_lines": null }
""" utility functionality for the 2D pharmacophores code See Docs/Chem/Pharm2D.triangles.jpg for an illustration of the way pharmacophores are broken into triangles and labelled. See Docs/Chem/Pharm2D.signatures.jpg for an illustration of bit numbering """ import numpy # # number of points in a scaffold -> sequence of distances (p1,p2) in # the scaffold # nPointDistDict = { 2: ((0,1),), 3: ((0,1),(0,2), (1,2)), 4: ((0,1),(0,2),(0,3), (1,2),(2,3)), 5: ((0,1),(0,2),(0,3),(0,4), (1,2),(2,3),(3,4)), 6: ((0,1),(0,2),(0,3),(0,4),(0,5), (1,2),(2,3),(3,4),(4,5)), 7: ((0,1),(0,2),(0,3),(0,4),(0,5),(0,6), (1,2),(2,3),(3,4),(4,5),(5,6)), 8: ((0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7), (1,2),(2,3),(3,4),(4,5),(5,6),(6,7)), 9: ((0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(0,8), (1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8)), 10: ((0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(0,8),(0,9), (1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9)), } # # number of distances in a scaffold -> number of points in the scaffold # nDistPointDict = { 1:2, 3:3, 5:4, 7:5, 9:6, 11:7, 13:8, 15:9, 17:10, } _trianglesInPharmacophore = {} def GetTriangles(nPts): """ returns a tuple with the distance indices for triangles composing an nPts-pharmacophore """ global _trianglesInPharmacophore if nPts < 3: return [] res = _trianglesInPharmacophore.get(nPts,[]) if not res: idx1,idx2,idx3=(0,1,nPts-1) while idx1<nPts-2: res.append((idx1,idx2,idx3)) idx1 += 1 idx2 += 1 idx3 += 1 res = tuple(res) _trianglesInPharmacophore[nPts] = res return res def _fact(x): if x <= 1: return 1 accum = 1 for i in range(x): accum *= i+1 return accum def BinsTriangleInequality(d1,d2,d3): """ checks the triangle inequality for combinations of distance bins. the general triangle inequality is: d1 + d2 >= d3 the conservative binned form of this is: d1(upper) + d2(upper) >= d3(lower) """ if d1[1]+d2[1]<d3[0]: return False if d2[1]+d3[1]<d1[0]: return False if d3[1]+d1[1]<d2[0]: return False return True def ScaffoldPasses(combo,bins=None): """ checks the scaffold passed in to see if all contributing triangles can satisfy the triangle inequality the scaffold itself (encoded in combo) is a list of binned distances """ # this is the number of points in the pharmacophore nPts = nDistPointDict[len(combo)] tris = GetTriangles(nPts) for tri in tris: ds = [bins[combo[x]] for x in tri] if not BinsTriangleInequality(ds[0],ds[1],ds[2]): return False return True _numCombDict = {} def NumCombinations(nItems,nSlots): """ returns the number of ways to fit nItems into nSlots We assume that (x,y) and (y,x) are equivalent, and (x,x) is allowed. General formula is, for N items and S slots: res = (N+S-1)! / ( (N-1)! * S! ) """ global _numCombDict res = _numCombDict.get((nItems,nSlots),-1) if res == -1: res = _fact(nItems+nSlots-1) / (_fact(nItems-1)*_fact(nSlots)) _numCombDict[(nItems,nSlots)] = res return res _verbose = 0 _countCache={} def CountUpTo(nItems,nSlots,vs,idx=0,startAt=0): """ Figures out where a given combination of indices would occur in the combinatorial explosion generated by _GetIndexCombinations_ **Arguments** - nItems: the number of items to distribute - nSlots: the number of slots in which to distribute them - vs: a sequence containing the values to find - idx: used in the recursion - startAt: used in the recursion **Returns** an integer """ global _countCache if _verbose: print ' '*idx,'CountUpTo(%d)'%idx,vs[idx],startAt if idx==0 and _countCache.has_key((nItems,nSlots,tuple(vs))): return _countCache[(nItems,nSlots,tuple(vs))] elif idx >= nSlots: accum = 0 elif idx == nSlots-1: accum = vs[idx]-startAt else: accum = 0 # get the digit at idx correct for i in range(startAt,vs[idx]): nLevsUnder = nSlots-idx-1 nValsOver = nItems-i if _verbose: print ' '*idx,' ',i,nValsOver,nLevsUnder,\ NumCombinations(nValsOver,nLevsUnder) accum += NumCombinations(nValsOver,nLevsUnder) accum += CountUpTo(nItems,nSlots,vs,idx+1,vs[idx]) if _verbose: print ' '*idx,'>',accum if idx == 0: _countCache[(nItems,nSlots,tuple(vs))] = accum return accum _indexCombinations={} def GetIndexCombinations(nItems,nSlots,slot=0,lastItemVal=0): """ Generates all combinations of nItems in nSlots without including duplicates **Arguments** - nItems: the number of items to distribute - nSlots: the number of slots in which to distribute them - slot: used in recursion - lastItemVal: used in recursion **Returns** a list of lists """ global _indexCombinations if not slot and _indexCombinations.has_key((nItems,nSlots)): res = _indexCombinations[(nItems,nSlots)] elif slot >= nSlots: res = [] elif slot == nSlots-1: res = [[x] for x in range(lastItemVal,nItems)] else: res = [] for x in range(lastItemVal,nItems): tmp = GetIndexCombinations(nItems,nSlots,slot+1,x) for entry in tmp: res.append([x]+entry) if not slot: _indexCombinations[(nItems,nSlots)] = res return res def GetAllCombinations(choices,noDups=1,which=0): """ Does the combinatorial explosion of the possible combinations of the elements of _choices_. **Arguments** - choices: sequence of sequences with the elements to be enumerated - noDups: (optional) if this is nonzero, results with duplicates, e.g. (1,1,0), will not be generated - which: used in recursion **Returns** a list of lists >>> GetAllCombinations([(0,),(1,),(2,)]) [[0, 1, 2]] >>> GetAllCombinations([(0,),(1,3),(2,)]) [[0, 1, 2], [0, 3, 2]] >>> GetAllCombinations([(0,1),(1,3),(2,)]) [[0, 1, 2], [0, 3, 2], [1, 3, 2]] """ if which >= len(choices): res = [] elif which == len(choices)-1: res = [[x] for x in choices[which]] else: res = [] tmp = GetAllCombinations(choices,noDups=noDups, which=which+1) for thing in choices[which]: for other in tmp: if not noDups or thing not in other: res.append([thing]+other) return res def GetUniqueCombinations(choices,classes,which=0): """ Does the combinatorial explosion of the possible combinations of the elements of _choices_. """ assert len(choices)==len(classes) if which >= len(choices): res = [] elif which == len(choices)-1: res = [[(classes[which],x)] for x in choices[which]] else: res = [] tmp = GetUniqueCombinations(choices,classes, which=which+1) for thing in choices[which]: for other in tmp: idxThere=0 for x in other: if x[1]==thing:idxThere+=1 if not idxThere: newL = [(classes[which],thing)]+other newL.sort() if newL not in res: res.append(newL) return res def UniquifyCombinations(combos): """ uniquifies the combinations in the argument **Arguments**: - combos: a sequence of sequences **Returns** - a list of tuples containing the unique combos """ print '>>> u:',combos resD = {} for combo in combos: k = combo[:] k.sort() resD[tuple(k)] = tuple(combo) print ' >>> u:',resD.values() return resD.values() def GetPossibleScaffolds(nPts,bins,useTriangleInequality=True): """ gets all realizable scaffolds (passing the triangle inequality) with the given number of points and returns them as a list of tuples """ if nPts < 2: res = 0 elif nPts == 2: res = [(x,) for x in range(len(bins))] else: nDists = len(nPointDistDict[nPts]) combos = GetAllCombinations([range(len(bins))]*nDists,noDups=0) res = [] for combo in combos: if not useTriangleInequality or ScaffoldPasses(combo,bins): res.append(tuple(combo)) return res def OrderTriangle(featIndices,dists): """ put the distances for a triangle into canonical order It's easy if the features are all different: >>> OrderTriangle([0,2,4],[1,2,3]) ([0, 2, 4], [1, 2, 3]) It's trickiest if they are all the same: >>> OrderTriangle([0,0,0],[1,2,3]) ([0, 0, 0], [3, 2, 1]) >>> OrderTriangle([0,0,0],[2,1,3]) ([0, 0, 0], [3, 2, 1]) >>> OrderTriangle([0,0,0],[1,3,2]) ([0, 0, 0], [3, 2, 1]) >>> OrderTriangle([0,0,0],[3,1,2]) ([0, 0, 0], [3, 2, 1]) >>> OrderTriangle([0,0,0],[3,2,1]) ([0, 0, 0], [3, 2, 1]) >>> OrderTriangle([0,0,1],[3,2,1]) ([0, 0, 1], [3, 2, 1]) >>> OrderTriangle([0,0,1],[1,3,2]) ([0, 0, 1], [1, 3, 2]) >>> OrderTriangle([0,0,1],[1,2,3]) ([0, 0, 1], [1, 3, 2]) >>> OrderTriangle([0,0,1],[1,3,2]) ([0, 0, 1], [1, 3, 2]) """ if len(featIndices)!=3: raise ValueError,'bad indices' if len(dists)!=3: raise ValueError,'bad dists' fs = set(featIndices) if len(fs)==3: return featIndices,dists dSums=[0]*3 dSums[0] = dists[0]+dists[1] dSums[1] = dists[0]+dists[2] dSums[2] = dists[1]+dists[2] mD = max(dSums) if len(fs)==1: if dSums[0]==mD: if dists[0]>dists[1]: ireorder=(0,1,2) dreorder=(0,1,2) else: ireorder=(0,2,1) dreorder=(1,0,2) elif dSums[1]==mD: if dists[0]>dists[2]: ireorder=(1,0,2) dreorder=(0,2,1) else: ireorder=(1,2,0) dreorder=(2,0,1) else: if dists[1]>dists[2]: ireorder = (2,0,1) dreorder=(1,2,0) else: ireorder = (2,1,0) dreorder=(2,1,0) else: # two classes if featIndices[0]==featIndices[1]: if dists[1]>dists[2]: ireorder=(0,1,2) dreorder=(0,1,2) else: ireorder=(1,0,2) dreorder=(0,2,1) elif featIndices[0]==featIndices[2]: if dists[0]>dists[2]: ireorder=(0,1,2) dreorder=(0,1,2) else: ireorder=(2,1,0) dreorder=(2,1,0) else: #featIndices[1]==featIndices[2]: if dists[0]>dists[1]: ireorder=(0,1,2) dreorder=(0,1,2) else: ireorder=(0,2,1) dreorder=(1,0,2) dists = [dists[x] for x in dreorder] featIndices = [featIndices[x] for x in ireorder] return featIndices,dists #------------------------------------ # # 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/Pharm2D/Utils.py", "copies": "2", "size": "11067", "license": "bsd-3-clause", "hash": 1399642563091505200, "line_mean": 24.3830275229, "line_max": 78, "alpha_frac": 0.5827234119, "autogenerated": false, "ratio": 2.905487004463114, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4488210416363114, "avg_score": null, "num_lines": null }
""" Atom-based calculation of LogP and MR using Crippen's approach Reference: S. A. Wildman and G. M. Crippen *JCICS* _39_ 868-873 (1999) """ from __future__ import print_function import os from rdkit import RDConfig from rdkit import Chem from rdkit.Chem import rdMolDescriptors import numpy _smartsPatterns = {} _patternOrder = [] # this is the file containing the atom contributions defaultPatternFileName = os.path.join(RDConfig.RDDataDir,'Crippen.txt') def _ReadPatts(fileName): """ *Internal Use Only* parses the pattern list from the data file """ patts = {} order = [] with open(fileName,'r') as f: lines = f.readlines() for line in lines: if line[0] != '#': splitLine = line.split('\t') if len(splitLine)>=4 and splitLine[0] != '': sma = splitLine[1] if sma!='SMARTS': sma.replace('"','') p = Chem.MolFromSmarts(sma) if p: if len(splitLine[0])>1 and splitLine[0][1] not in 'S0123456789': cha = splitLine[0][:2] else: cha = splitLine[0][0] logP = float(splitLine[2]) if splitLine[3] != '': mr = float(splitLine[3]) else: mr = 0.0 if cha not in order: order.append(cha) l = patts.get(cha,[]) l.append((sma,p,logP,mr)) patts[cha] = l else: print('Problems parsing smarts: %s'%(sma)) return order,patts _GetAtomContribs=rdMolDescriptors._CalcCrippenContribs def _pyGetAtomContribs(mol,patts=None,order=None,verbose=0,force=0): """ *Internal Use Only* calculates atomic contributions to the LogP and MR values if the argument *force* is not set, we'll use the molecules stored _crippenContribs value when possible instead of re-calculating. **Note:** Changes here affect the version numbers of MolLogP and MolMR as well as the VSA descriptors in Chem.MolSurf """ if not force and hasattr(mol,'_crippenContribs'): return mol._crippenContribs if patts is None: patts = _smartsPatterns order = _patternOrder nAtoms = mol.GetNumAtoms() atomContribs = [(0.,0.)]*nAtoms doneAtoms=[0]*nAtoms nAtomsFound=0 done = False for cha in order: pattVect = patts[cha] for sma,patt,logp,mr in pattVect: #print('try:',entry[0]) for match in mol.GetSubstructMatches(patt,False,False): firstIdx = match[0] if not doneAtoms[firstIdx]: doneAtoms[firstIdx]=1 atomContribs[firstIdx] = (logp,mr) if verbose: print('\tAtom %d: %s %4.4f %4.4f'%(match[0],sma,logp,mr)) nAtomsFound+=1 if nAtomsFound>=nAtoms: done=True break if done: break mol._crippenContribs = atomContribs return atomContribs def _Init(): global _smartsPatterns,_patternOrder if _smartsPatterns == {}: _patternOrder,_smartsPatterns = _ReadPatts(defaultPatternFileName) def _pyMolLogP(inMol,patts=None,order=None,verbose=0,addHs=1): """ DEPRECATED """ if addHs < 0: mol = Chem.AddHs(inMol,1) elif addHs > 0: mol = Chem.AddHs(inMol,0) else: mol = inMol if patts is None: global _smartsPatterns,_patternOrder if _smartsPatterns == {}: _patternOrder,_smartsPatterns = _ReadPatts(defaultPatternFileName) patts = _smartsPatterns order = _patternOrder atomContribs = _pyGetAtomContribs(mol,patts,order,verbose=verbose) return numpy.sum(atomContribs,0)[0] _pyMolLogP.version="1.1.0" def _pyMolMR(inMol,patts=None,order=None,verbose=0,addHs=1): """ DEPRECATED """ if addHs < 0: mol = Chem.AddHs(inMol,1) elif addHs > 0: mol = Chem.AddHs(inMol,0) else: mol = inMol if patts is None: global _smartsPatterns,_patternOrder if _smartsPatterns == {}: _patternOrder,_smartsPatterns = _ReadPatts(defaultPatternFileName) patts = _smartsPatterns order = _patternOrder atomContribs = _pyGetAtomContribs(mol,patts,order,verbose=verbose) return numpy.sum(atomContribs,0)[1] _pyMolMR.version="1.1.0" MolLogP=lambda *x,**y:rdMolDescriptors.CalcCrippenDescriptors(*x,**y)[0] MolLogP.version=rdMolDescriptors._CalcCrippenDescriptors_version MolLogP.__doc__=""" Wildman-Crippen LogP value Uses an atom-based scheme based on the values in the paper: S. A. Wildman and G. M. Crippen JCICS 39 868-873 (1999) **Arguments** - inMol: a molecule - addHs: (optional) toggles adding of Hs to the molecule for the calculation. If true, hydrogens will be added to the molecule and used in the calculation. """ MolMR=lambda *x,**y:rdMolDescriptors.CalcCrippenDescriptors(*x,**y)[1] MolMR.version=rdMolDescriptors._CalcCrippenDescriptors_version MolMR.__doc__=""" Wildman-Crippen MR value Uses an atom-based scheme based on the values in the paper: S. A. Wildman and G. M. Crippen JCICS 39 868-873 (1999) **Arguments** - inMol: a molecule - addHs: (optional) toggles adding of Hs to the molecule for the calculation. If true, hydrogens will be added to the molecule and used in the calculation. """ if __name__=='__main__': import sys if len(sys.argv): ms = [] verbose=0 if '-v' in sys.argv: verbose=1 sys.argv.remove('-v') for smi in sys.argv[1:]: ms.append((smi,Chem.MolFromSmiles(smi))) for smi,m in ms: print('Mol: %s'%(smi)) logp = MolLogP(m,verbose=verbose) print('----') mr = MolMR(m,verbose=verbose) print('Res:',logp,mr) newM = Chem.AddHs(m) logp = MolLogP(newM,addHs=0) mr = MolMR(newM,addHs=0) print('\t',logp,mr) print('-*-*-*-*-*-*-*-*')
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/Crippen.py", "copies": "1", "size": "6023", "license": "bsd-3-clause", "hash": 9088291811387158000, "line_mean": 27.4103773585, "line_max": 83, "alpha_frac": 0.6390503072, "autogenerated": false, "ratio": 3.044994944388271, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9045608049443625, "avg_score": 0.027687440428929136, "num_lines": 212 }
""" Atom-based calculation of LogP and MR using Crippen's approach Reference: S. A. Wildman and G. M. Crippen *JCICS* _39_ 868-873 (1999) """ import os from rdkit import RDConfig from rdkit import Chem from rdkit.Chem import rdMolDescriptors import numpy _smartsPatterns = {} _patternOrder = [] # this is the file containing the atom contributions defaultPatternFileName = os.path.join(RDConfig.RDDataDir,'Crippen.txt') def _ReadPatts(fileName): """ *Internal Use Only* parses the pattern list from the data file """ patts = {} order = [] for line in open(fileName,'r').xreadlines(): if line[0] != '#': splitLine = line.split('\t') if len(splitLine)>=4 and splitLine[0] != '': sma = splitLine[1] if sma!='SMARTS': sma.replace('"','') try: p = Chem.MolFromSmarts(sma) except: pass else: if p: if len(splitLine[0])>1 and splitLine[0][1] not in 'S0123456789': cha = splitLine[0][:2] else: cha = splitLine[0][0] logP = float(splitLine[2]) if splitLine[3] != '': mr = float(splitLine[3]) else: mr = 0.0 if cha not in order: order.append(cha) l = patts.get(cha,[]) l.append((sma,p,logP,mr)) patts[cha] = l else: print 'Problems parsing smarts: %s'%(sma) return order,patts _GetAtomContribs=rdMolDescriptors._CalcCrippenContribs def _pyGetAtomContribs(mol,patts=None,order=None,verbose=0,force=0): """ *Internal Use Only* calculates atomic contributions to the LogP and MR values if the argument *force* is not set, we'll use the molecules stored _crippenContribs value when possible instead of re-calculating. **Note:** Changes here affect the version numbers of MolLogP and MolMR as well as the VSA descriptors in Chem.MolSurf """ if not force and hasattr(mol,'_crippenContribs'): return mol._crippenContribs if patts is None: patts = _smartsPatterns order = _patternOrder nAtoms = mol.GetNumAtoms() atomContribs = [(0.,0.)]*nAtoms doneAtoms=[0]*nAtoms nAtomsFound=0 done = False for cha in order: pattVect = patts[cha] for sma,patt,logp,mr in pattVect: #print 'try:',entry[0] for match in mol.GetSubstructMatches(patt,False,False): firstIdx = match[0] if not doneAtoms[firstIdx]: doneAtoms[firstIdx]=1 atomContribs[firstIdx] = (logp,mr) if verbose: print '\tAtom %d: %s %4.4f %4.4f'%(match[0],sma,logp,mr) nAtomsFound+=1 if nAtomsFound>=nAtoms: done=True break if done: break mol._crippenContribs = atomContribs return atomContribs def _Init(): global _smartsPatterns,_patternOrder if _smartsPatterns == {}: _patternOrder,_smartsPatterns = _ReadPatts(defaultPatternFileName) def _pyMolLogP(inMol,patts=None,order=None,verbose=0,addHs=1): """ DEPRECATED """ if addHs < 0: mol = Chem.AddHs(inMol,1) elif addHs > 0: mol = Chem.AddHs(inMol,0) else: mol = inMol if patts is None: global _smartsPatterns,_patternOrder if _smartsPatterns == {}: _patternOrder,_smartsPatterns = _ReadPatts(defaultPatternFileName) patts = _smartsPatterns order = _patternOrder atomContribs = _pyGetAtomContribs(mol,patts,order,verbose=verbose) return numpy.sum(atomContribs,0)[0] _pyMolLogP.version="1.1.0" def _pyMolMR(inMol,patts=None,order=None,verbose=0,addHs=1): """ DEPRECATED """ if addHs < 0: mol = Chem.AddHs(inMol,1) elif addHs > 0: mol = Chem.AddHs(inMol,0) else: mol = inMol if patts is None: global _smartsPatterns,_patternOrder if _smartsPatterns == {}: _patternOrder,_smartsPatterns = _ReadPatts(defaultPatternFileName) patts = _smartsPatterns order = _patternOrder atomContribs = _pyGetAtomContribs(mol,patts,order,verbose=verbose) return numpy.sum(atomContribs,0)[1] _pyMolMR.version="1.1.0" MolLogP=lambda *x,**y:rdMolDescriptors.CalcCrippenDescriptors(*x,**y)[0] MolLogP.version=rdMolDescriptors._CalcCrippenDescriptors_version MolLogP.__doc__=""" Wildman-Crippen LogP value Uses an atom-based scheme based on the values in the paper: S. A. Wildman and G. M. Crippen JCICS 39 868-873 (1999) **Arguments** - inMol: a molecule - addHs: (optional) toggles adding of Hs to the molecule for the calculation. If true, hydrogens will be added to the molecule and used in the calculation. """ MolMR=lambda *x,**y:rdMolDescriptors.CalcCrippenDescriptors(*x,**y)[1] MolMR.version=rdMolDescriptors._CalcCrippenDescriptors_version MolMR.__doc__=""" Wildman-Crippen MR value Uses an atom-based scheme based on the values in the paper: S. A. Wildman and G. M. Crippen JCICS 39 868-873 (1999) **Arguments** - inMol: a molecule - addHs: (optional) toggles adding of Hs to the molecule for the calculation. If true, hydrogens will be added to the molecule and used in the calculation. """ if __name__=='__main__': import sys if len(sys.argv): ms = [] verbose=0 if '-v' in sys.argv: verbose=1 sys.argv.remove('-v') for smi in sys.argv[1:]: ms.append((smi,Chem.MolFromSmiles(smi))) for smi,m in ms: print 'Mol: %s'%(smi) logp = MolLogP(m,verbose=verbose) print '----' mr = MolMR(m,verbose=verbose) print 'Res:',logp,mr newM = Chem.AddHs(m) logp = MolLogP(newM,addHs=0) mr = MolMR(newM,addHs=0) print '\t',logp,mr print '-*-*-*-*-*-*-*-*'
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Crippen.py", "copies": "2", "size": "6051", "license": "bsd-3-clause", "hash": 4060617700235010000, "line_mean": 27.4084507042, "line_max": 83, "alpha_frac": 0.6313006115, "autogenerated": false, "ratio": 3.0762582613116423, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4707558872811643, "avg_score": null, "num_lines": null }
""" command line utility to report on the contributions of descriptors to tree-based composite models Usage: AnalyzeComposite [optional args] <models> <models>: file name(s) of pickled composite model(s) (this is the name of the db table if using a database) Optional Arguments: -n number: the number of levels of each model to consider -d dbname: the database from which to read the models -N Note: the note string to search for to pull models from the database -v: be verbose whilst screening """ from __future__ import print_function import numpy import sys from rdkit.six.moves import cPickle from rdkit.ML.DecTree import TreeUtils,Tree from rdkit.ML.Data import Stats from rdkit.Dbase.DbConnection import DbConnect from rdkit.ML import ScreenComposite __VERSION_STRING="2.2.0" def ProcessIt(composites,nToConsider=3,verbose=0): composite=composites[0] nComposites =len(composites) ns = composite.GetDescriptorNames() #nDesc = len(ns)-2 if len(ns)>2: globalRes = {} nDone = 1 descNames = {} for composite in composites: if verbose > 0: print('#------------------------------------') print('Doing: ',nDone) nModels = len(composite) nDone += 1 res = {} for i in range(len(composite)): model = composite.GetModel(i) if isinstance(model,Tree.TreeNode): levels = TreeUtils.CollectLabelLevels(model,{},0,nToConsider) TreeUtils.CollectDescriptorNames(model,descNames,0,nToConsider) for descId in levels.keys(): v = res.get(descId,numpy.zeros(nToConsider,numpy.float)) v[levels[descId]] += 1./nModels res[descId] = v for k in res: v = globalRes.get(k,numpy.zeros(nToConsider,numpy.float)) v += res[k]/nComposites globalRes[k] = v if verbose > 0: for k in res.keys(): name = descNames[k] strRes = ', '.join(['%4.2f'%x for x in res[k]]) print('%s,%s,%5.4f'%(name,strRes,sum(res[k]))) print() if verbose >= 0: print('# Average Descriptor Positions') retVal = [] for k in globalRes.keys(): name = descNames[k] if verbose >= 0: strRes = ', '.join(['%4.2f'%x for x in globalRes[k]]) print('%s,%s,%5.4f'%(name,strRes,sum(globalRes[k]))) tmp = [name] tmp.extend(globalRes[k]) tmp.append(sum(globalRes[k])) retVal.append(tmp) if verbose >= 0: print() else: retVal = [] return retVal def ErrorStats(conn,where,enrich=1): fields = 'overall_error,holdout_error,overall_result_matrix,holdout_result_matrix,overall_correct_conf,overall_incorrect_conf,holdout_correct_conf,holdout_incorrect_conf' try: data = conn.GetData(fields=fields,where=where) except: import traceback traceback.print_exc() return None nPts = len(data) if not nPts: sys.stderr.write('no runs found\n') return None overall = numpy.zeros(nPts,numpy.float) overallEnrich = numpy.zeros(nPts,numpy.float) oCorConf = 0.0 oInCorConf = 0.0 holdout = numpy.zeros(nPts,numpy.float) holdoutEnrich = numpy.zeros(nPts,numpy.float) hCorConf = 0.0 hInCorConf = 0.0 overallMatrix = None holdoutMatrix = None for i in range(nPts): if data[i][0] is not None: overall[i] = data[i][0] oCorConf += data[i][4] oInCorConf += data[i][5] if data[i][1] is not None: holdout[i] = data[i][1] haveHoldout=1 else: haveHoldout=0 tmpOverall = 1.*eval(data[i][2]) if enrich >=0: overallEnrich[i] = ScreenComposite.CalcEnrichment(tmpOverall,tgt=enrich) if haveHoldout: tmpHoldout = 1.*eval(data[i][3]) if enrich >=0: holdoutEnrich[i] = ScreenComposite.CalcEnrichment(tmpHoldout,tgt=enrich) if overallMatrix is None: if data[i][2] is not None: overallMatrix = tmpOverall if haveHoldout and data[i][3] is not None: holdoutMatrix = tmpHoldout else: overallMatrix += tmpOverall if haveHoldout: holdoutMatrix += tmpHoldout if haveHoldout: hCorConf += data[i][6] hInCorConf += data[i][7] avgOverall = sum(overall)/nPts oCorConf /= nPts oInCorConf /= nPts overallMatrix /= nPts oSort = numpy.argsort(overall) oMin = overall[oSort[0]] overall -= avgOverall devOverall = sqrt(sum(overall**2)/(nPts-1)) res = {} res['oAvg'] = 100*avgOverall res['oDev'] = 100*devOverall res['oCorrectConf'] = 100*oCorConf res['oIncorrectConf'] = 100*oInCorConf res['oResultMat']=overallMatrix res['oBestIdx']=oSort[0] res['oBestErr']=100*oMin if enrich>=0: mean,dev = Stats.MeanAndDev(overallEnrich) res['oAvgEnrich'] = mean res['oDevEnrich'] = dev if haveHoldout: avgHoldout = sum(holdout)/nPts hCorConf /= nPts hInCorConf /= nPts holdoutMatrix /= nPts hSort = numpy.argsort(holdout) hMin = holdout[hSort[0]] holdout -= avgHoldout devHoldout = sqrt(sum(holdout**2)/(nPts-1)) res['hAvg'] = 100*avgHoldout res['hDev'] = 100*devHoldout res['hCorrectConf'] = 100*hCorConf res['hIncorrectConf'] = 100*hInCorConf res['hResultMat']=holdoutMatrix res['hBestIdx']=hSort[0] res['hBestErr']=100*hMin if enrich>=0: mean,dev = Stats.MeanAndDev(holdoutEnrich) res['hAvgEnrich'] = mean res['hDevEnrich'] = dev return res def ShowStats(statD,enrich=1): statD = statD.copy() statD['oBestIdx'] = statD['oBestIdx']+1 txt=""" # Error Statistics: \tOverall: %(oAvg)6.3f%% (%(oDev)6.3f) %(oCorrectConf)4.1f/%(oIncorrectConf)4.1f \t\tBest: %(oBestIdx)d %(oBestErr)6.3f%%"""%(statD) if 'hAvg' in statD: statD['hBestIdx'] = statD['hBestIdx']+1 txt += """ \tHoldout: %(hAvg)6.3f%% (%(hDev)6.3f) %(hCorrectConf)4.1f/%(hIncorrectConf)4.1f \t\tBest: %(hBestIdx)d %(hBestErr)6.3f%% """%(statD) print(txt) print() print('# Results matrices:') print('\tOverall:') tmp = transpose(statD['oResultMat']) colCounts = sum(tmp) rowCounts = sum(tmp,1) for i in range(len(tmp)): if rowCounts[i]==0: rowCounts[i]=1 row = tmp[i] print('\t\t', end='') for j in range(len(row)): print('% 6.2f'%row[j], end='') print('\t| % 4.2f'%(100.*tmp[i,i]/rowCounts[i])) print('\t\t', end='') for i in range(len(tmp)): print('------',end='') print() print('\t\t',end='') for i in range(len(tmp)): if colCounts[i]==0: colCounts[i]=1 print('% 6.2f'%(100.*tmp[i,i]/colCounts[i]), end='') print() if enrich>-1 and 'oAvgEnrich' in statD: print('\t\tEnrich(%d): %.3f (%.3f)'%(enrich,statD['oAvgEnrich'],statD['oDevEnrich'])) if 'hResultMat' in statD: print('\tHoldout:') tmp = transpose(statD['hResultMat']) colCounts = sum(tmp) rowCounts = sum(tmp,1) for i in range(len(tmp)): if rowCounts[i]==0: rowCounts[i]=1 row = tmp[i] print('\t\t', end='') for j in range(len(row)): print('% 6.2f'%row[j], end='') print('\t| % 4.2f'%(100.*tmp[i,i]/rowCounts[i])) print('\t\t',end='') for i in range(len(tmp)): print('------',end='') print() print('\t\t',end='') for i in range(len(tmp)): if colCounts[i]==0: colCounts[i]=1 print('% 6.2f'%(100.*tmp[i,i]/colCounts[i]),end='') print() if enrich>-1 and 'hAvgEnrich' in statD: print('\t\tEnrich(%d): %.3f (%.3f)'%(enrich,statD['hAvgEnrich'],statD['hDevEnrich'])) return def Usage(): print(__doc__) sys.exit(-1) if __name__ == "__main__": import getopt try: args,extras = getopt.getopt(sys.argv[1:],'n:d:N:vX',('skip', 'enrich=', )) except: Usage() count = 3 db = None note = '' verbose = 0 skip = 0 enrich = 1 for arg,val in args: if arg == '-n': count = int(val)+1 elif arg == '-d': db = val elif arg == '-N': note = val elif arg == '-v': verbose = 1 elif arg == '--skip': skip = 1 elif arg == '--enrich': enrich = int(val) composites = [] if db is None: for arg in extras: composite = cPickle.load(open(arg,'rb')) composites.append(composite) else: tbl = extras[0] conn = DbConnect(db,tbl) if note: where="where note='%s'"%(note) else: where = '' if not skip: pkls = conn.GetData(fields='model',where=where) composites = [] for pkl in pkls: pkl = str(pkl[0]) comp = cPickle.loads(pkl) composites.append(comp) if len(composites): ProcessIt(composites,count,verbose=verbose) elif not skip: print('ERROR: no composite models found') sys.exit(-1) if db: res = ErrorStats(conn,where,enrich=enrich) if res: ShowStats(res)
{ "repo_name": "strets123/rdkit", "path": "rdkit/ML/AnalyzeComposite.py", "copies": "3", "size": "9195", "license": "bsd-3-clause", "hash": -7755896508726708000, "line_mean": 27.2923076923, "line_max": 172, "alpha_frac": 0.5973898858, "autogenerated": false, "ratio": 3.0835010060362174, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.034343268199152836, "num_lines": 325 }
""" generation of 2D pharmacophores **Notes** - The terminology for this gets a bit rocky, so here's a glossary of what terms used here mean: 1) *N-point pharmacophore* a combination of N features along with distances betwen them. 2) *N-point proto-pharmacophore*: a combination of N feature definitions without distances. Each N-point proto-pharmacophore defines a manifold of potential N-point pharmacophores. 3) *N-point scaffold*: a collection of the distances defining an N-point pharmacophore without feature identities. See Docs/Chem/Pharm2D.triangles.jpg for an illustration of the way pharmacophores are broken into triangles and labelled. See Docs/Chem/Pharm2D.signatures.jpg for an illustration of bit numbering """ from __future__ import print_function from rdkit.Chem.Pharm2D import Utils, SigFactory from rdkit.RDLogger import logger logger = logger() _verbose = 0 def _ShortestPathsMatch(match, featureSet, sig, dMat, sigFactory): """ Internal use only """ if _verbose: print('match:', match) nPts = len(match) distsToCheck = Utils.nPointDistDict[nPts] nDists = len(distsToCheck) dist = [0] * nDists bins = sigFactory.GetBins() minD, maxD = bins[0][0], bins[-1][1] for i in range(nDists): pt0, pt1 = distsToCheck[i] minSeen = maxD for idx1 in match[pt0]: for idx2 in match[pt1]: minSeen = min(minSeen, dMat[idx1, idx2]) if minSeen == 0 or minSeen < minD: return # FIX: this won't be an int if we're using the bond order. d = int(minSeen) # do a quick distance filter if d == 0 or d < minD or d >= maxD: return dist[i] = d idx = sigFactory.GetBitIdx(featureSet, dist, sortIndices=False) if _verbose: print('\t', dist, minD, maxD, idx) if sigFactory.useCounts: sig[idx] = sig[idx] + 1 else: sig.SetBit(idx) return idx def Gen2DFingerprint(mol, sigFactory, perms=None, dMat=None, bitInfo=None): """ generates a 2D fingerprint for a molecule using the parameters in _sig_ **Arguments** - mol: the molecule for which the signature should be generated - sigFactory : the SigFactory object with signature parameters NOTE: no preprocessing is carried out for _sigFactory_. It *must* be pre-initialized. - perms: (optional) a sequence of permutation indices limiting which pharmacophore combinations are allowed - dMat: (optional) the distance matrix to be used - bitInfo: (optional) used to return the atoms involved in the bits """ if not isinstance(sigFactory, SigFactory.SigFactory): raise ValueError('bad factory') featFamilies = sigFactory.GetFeatFamilies() if _verbose: print('* feat famillies:', featFamilies) nFeats = len(featFamilies) minCount = sigFactory.minPointCount maxCount = sigFactory.maxPointCount if maxCount > 3: logger.warning( ' Pharmacophores with more than 3 points are not currently supported.\nSetting maxCount to 3.') maxCount = 3 # generate the molecule's distance matrix, if required if dMat is None: from rdkit import Chem useBO = sigFactory.includeBondOrder dMat = Chem.GetDistanceMatrix(mol, useBO) # generate the permutations, if required if perms is None: perms = [] for count in range(minCount, maxCount + 1): perms += Utils.GetIndexCombinations(nFeats, count) # generate the matches: featMatches = sigFactory.GetMolFeats(mol) if _verbose: print(' featMatches:', featMatches) sig = sigFactory.GetSignature() for perm in perms: # the permutation is a combination of feature indices # defining the feature set for a proto-pharmacophore featClasses = [0] for i in range(1, len(perm)): if perm[i] == perm[i - 1]: featClasses.append(featClasses[-1]) else: featClasses.append(featClasses[-1] + 1) # Get a set of matches at each index of # the proto-pharmacophore. matchPerms = [featMatches[x] for x in perm] if _verbose: print('\n->Perm: %s' % (str(perm))) print(' matchPerms: %s' % (str(matchPerms))) # Get all unique combinations of those possible matches: matchesToMap = Utils.GetUniqueCombinations(matchPerms, featClasses) for i, entry in enumerate(matchesToMap): entry = [x[1] for x in entry] matchesToMap[i] = entry if _verbose: print(' mtM:', matchesToMap) for match in matchesToMap: if sigFactory.shortestPathsOnly: idx = _ShortestPathsMatch(match, perm, sig, dMat, sigFactory) if idx is not None and bitInfo is not None: l = bitInfo.get(idx, []) l.append(match) bitInfo[idx] = l return sig
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Pharm2D/Generate.py", "copies": "1", "size": "5078", "license": "bsd-3-clause", "hash": -7669428762973347000, "line_mean": 29.5903614458, "line_max": 101, "alpha_frac": 0.6738873572, "autogenerated": false, "ratio": 3.475701574264203, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46495889314642025, "avg_score": null, "num_lines": null }
"""unit testing code for the Crippen clogp and MR calculators """ from __future__ import print_function import unittest,sys,os import io import numpy from rdkit import RDConfig from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import Crippen def feq(n1,n2,tol=1e-5): return abs(n1-n2)<=tol class TestCase(unittest.TestCase): def setUp(self): self.fName = os.path.join(RDConfig.RDCodeDir,'Chem/test_data','Crippen.csv') self.detailName = os.path.join(RDConfig.RDCodeDir,'Chem/test_data','Crippen_contribs_regress.pkl') self.detailName2 = os.path.join(RDConfig.RDCodeDir,'Chem/test_data','Crippen_contribs_regress.2.pkl') def _readData(self): smis=[] clogs=[] mrs=[] with open(self.fName,'r') as f: lines = f.readlines() for line in lines: if len(line) and line[0] != '#': splitL = line.split(',') if len(splitL)==3: smi,clog,mr=splitL smis.append(smi) clogs.append(float(clog)) mrs.append(float(mr)) self.smis = smis self.clogs = clogs self.mrs = mrs def testLogP(self): self._readData() nMols = len(self.smis) #outF = file(self.fName,'w') for i in range(nMols): smi = self.smis[i] mol = Chem.MolFromSmiles(smi) if 1: clog = self.clogs[i] tmp = Crippen.MolLogP(mol) self.assertTrue(feq(clog,tmp),'bad logp for %s: %4.4f != %4.4f'%(smi,clog,tmp)) mr = self.mrs[i] tmp = Crippen.MolMR(mol) self.assertTrue(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) else: clog = Crippen.MolLogP(mol) mr = Crippen.MolMR(mol) print('%s,%.4f,%.4f'%(smi,clog,mr), file=outF) def testRepeat(self): self._readData() nMols = len(self.smis) for i in range(nMols): smi = self.smis[i] mol = Chem.MolFromSmiles(smi) clog = self.clogs[i] tmp = Crippen.MolLogP(mol) tmp = Crippen.MolLogP(mol) self.assertTrue(feq(clog,tmp),'bad logp fooutF,r %s: %4.4f != %4.4f'%(smi,clog,tmp)) mr = self.mrs[i] tmp = Crippen.MolMR(mol) tmp = Crippen.MolMR(mol) self.assertTrue(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) def _writeDetailFile(self,inF,outF): while 1: try: smi,refContribs = cPickle.load(inF) except EOFError: break else: mol = Chem.MolFromSmiles(smi) if mol: mol=Chem.AddHs(mol,1) smi2 = Chem.MolToSmiles(mol) contribs = Crippen._GetAtomContribs(mol) cPickle.dump((smi,contribs),outF) else: print('Problems with SMILES:',smi) def _doDetailFile(self,inF,nFailsAllowed=1): done = 0 verbose=0 nFails=0 while not done: if verbose: print('---------------') try: smi,refContribs = cPickle.load(inF) except EOFError: done = 1 else: refContribs = [x[0] for x in refContribs] refOrder= numpy.argsort(refContribs) mol = Chem.MolFromSmiles(smi) if mol: mol=Chem.AddHs(mol,1) smi2 = Chem.MolToSmiles(mol) contribs = Crippen._GetAtomContribs(mol) contribs = [x[0] for x in contribs] # # we're comparing to the old results using the oelib code. # Since we have some disagreements with them as to what is # aromatic and what isn't, we may have different numbers of # Hs. For the sake of comparison, just pop those off our # new results. # while len(contribs)>len(refContribs): del contribs[-1] order = numpy.argsort(contribs) for i in range(len(refContribs)): refL = refContribs[refOrder[i]] l = contribs[order[i]] if not feq(refL,l): print('%s (%s): %d %6.5f != %6.5f'%(smi,smi2,order[i],refL,l)) Crippen._GetAtomContribs(mol,force=1) print('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*') nFails +=1 break; else: print('Problems with SMILES:',smi) self.assertTrue(nFails<nFailsAllowed) def testDetails(self): Crippen._Init() with open(self.detailName,'r') as inTF: buf = inTF.read().replace('\r\n', '\n').encode('utf-8') inTF.close() with io.BytesIO(buf) as inF: if 0: outF = open('tmp.pkl','wb+') self._writeDetailFile(inF,outF) self._doDetailFile(inF) def testDetails2(self): Crippen._Init() with open(self.detailName2,'r') as inTF: buf = inTF.read().replace('\r\n', '\n').encode('utf-8') inTF.close() with io.BytesIO(buf) as inF: if 0: outF = open('tmp.pkl','wb+') self._writeDetailFile(inF,outF) self._doDetailFile(inF) def testIssue80(self): from rdkit.Chem import Lipinski m = Chem.MolFromSmiles('CCOC') ref = Crippen.MolLogP(m) Lipinski.NHOHCount(m) probe = Crippen.MolLogP(m) self.assertTrue(probe==ref) def testIssue1749494(self): m1 = Chem.MolFromSmiles('[*]CC') v = Crippen.MolLogP(m1) self.assertTrue(feq(v,0.9739)) if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/UnitTestCrippen.py", "copies": "1", "size": "5578", "license": "bsd-3-clause", "hash": 1608669888562862300, "line_mean": 28.8288770053, "line_max": 105, "alpha_frac": 0.5790605952, "autogenerated": false, "ratio": 2.864920390344119, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8743413100353705, "avg_score": 0.04011357703808269, "num_lines": 187 }
"""unit testing code for the Crippen clogp and MR calculators """ from __future__ import print_function import unittest,sys,os import numpy from rdkit import RDConfig from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import Crippen def feq(n1,n2,tol=1e-5): return abs(n1-n2)<=tol class TestCase(unittest.TestCase): def setUp(self): self.fName = os.path.join(RDConfig.RDCodeDir,'Chem/test_data','Crippen.csv') self.detailName = os.path.join(RDConfig.RDCodeDir,'Chem/test_data','Crippen_contribs_regress.pkl') self.detailName2 = os.path.join(RDConfig.RDCodeDir,'Chem/test_data','Crippen_contribs_regress.2.pkl') def _readData(self): smis=[] clogs=[] mrs=[] with open(self.fName,'r') as f: lines = f.readlines() for line in lines: if len(line) and line[0] != '#': splitL = line.split(',') if len(splitL)==3: smi,clog,mr=splitL smis.append(smi) clogs.append(float(clog)) mrs.append(float(mr)) self.smis = smis self.clogs = clogs self.mrs = mrs def testLogP(self): self._readData() nMols = len(self.smis) #outF = file(self.fName,'w') for i in range(nMols): smi = self.smis[i] mol = Chem.MolFromSmiles(smi) if 1: clog = self.clogs[i] tmp = Crippen.MolLogP(mol) self.assertTrue(feq(clog,tmp),'bad logp for %s: %4.4f != %4.4f'%(smi,clog,tmp)) mr = self.mrs[i] tmp = Crippen.MolMR(mol) self.assertTrue(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) else: clog = Crippen.MolLogP(mol) mr = Crippen.MolMR(mol) print('%s,%.4f,%.4f'%(smi,clog,mr), file=outF) def testRepeat(self): self._readData() nMols = len(self.smis) for i in range(nMols): smi = self.smis[i] mol = Chem.MolFromSmiles(smi) clog = self.clogs[i] tmp = Crippen.MolLogP(mol) tmp = Crippen.MolLogP(mol) self.assertTrue(feq(clog,tmp),'bad logp fooutF,r %s: %4.4f != %4.4f'%(smi,clog,tmp)) mr = self.mrs[i] tmp = Crippen.MolMR(mol) tmp = Crippen.MolMR(mol) self.assertTrue(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) def _writeDetailFile(self,inF,outF): while 1: try: smi,refContribs = cPickle.load(inF) except EOFError: break else: try: mol = Chem.MolFromSmiles(smi) except: import traceback traceback.print_exc() mol = None if mol: mol=Chem.AddHs(mol,1) smi2 = Chem.MolToSmiles(mol) contribs = Crippen._GetAtomContribs(mol) cPickle.dump((smi,contribs),outF) else: print('Problems with SMILES:',smi) def _doDetailFile(self,inF,nFailsAllowed=1): done = 0 verbose=0 nFails=0 while not done: if verbose: print('---------------') try: smi,refContribs = cPickle.load(inF) except EOFError: done = 1 else: refContribs = [x[0] for x in refContribs] refOrder= numpy.argsort(refContribs) try: mol = Chem.MolFromSmiles(smi) except: import traceback traceback.print_exc() mol = None if mol: mol=Chem.AddHs(mol,1) smi2 = Chem.MolToSmiles(mol) contribs = Crippen._GetAtomContribs(mol) contribs = [x[0] for x in contribs] # # we're comparing to the old results using the oelib code. # Since we have some disagreements with them as to what is # aromatic and what isn't, we may have different numbers of # Hs. For the sake of comparison, just pop those off our # new results. # while len(contribs)>len(refContribs): del contribs[-1] order = numpy.argsort(contribs) for i in range(len(refContribs)): refL = refContribs[refOrder[i]] l = contribs[order[i]] if not feq(refL,l): print('%s (%s): %d %6.5f != %6.5f'%(smi,smi2,order[i],refL,l)) Crippen._GetAtomContribs(mol,force=1) print('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*') nFails +=1 break; else: print('Problems with SMILES:',smi) self.assertTrue(nFails<nFailsAllowed) def testDetails(self): Crippen._Init() with open(self.detailName,'rb') as inF: if 0: outF = open('tmp.pkl','wb+') self._writeDetailFile(inF,outF) self._doDetailFile(inF) def testDetails2(self): Crippen._Init() with open(self.detailName2,'rb') as inF: if 0: outF = open('tmp.pkl','wb+') self._writeDetailFile(inF,outF) self._doDetailFile(inF) def testIssue80(self): from rdkit.Chem import Lipinski m = Chem.MolFromSmiles('CCOC') ref = Crippen.MolLogP(m) Lipinski.NHOHCount(m) probe = Crippen.MolLogP(m) self.assertTrue(probe==ref) def testIssue1749494(self): m1 = Chem.MolFromSmiles('[*]CC') v = Crippen.MolLogP(m1) self.assertTrue(feq(v,0.9739)) if __name__ == '__main__': unittest.main()
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/UnitTestCrippen.py", "copies": "1", "size": "5562", "license": "bsd-3-clause", "hash": -7561816055630777000, "line_mean": 28.2736842105, "line_max": 105, "alpha_frac": 0.5746134484, "autogenerated": false, "ratio": 2.9242902208201893, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3998903669220189, "avg_score": null, "num_lines": null }
"""unit testing code for the Crippen clogp and MR calculators """ from rdkit import RDConfig import unittest,sys,os,cPickle from rdkit import Chem from rdkit.Chem import Crippen import numpy def feq(n1,n2,tol=1e-5): return abs(n1-n2)<=tol class TestCase(unittest.TestCase): def setUp(self): self.fName = os.path.join(RDConfig.RDCodeDir,'Chem/tests','Crippen.csv') self.detailName = os.path.join(RDConfig.RDCodeDir,'Chem/tests','Crippen_contribs_regress.pkl') self.detailName2 = os.path.join(RDConfig.RDCodeDir,'Chem/tests','Crippen_contribs_regress.2.pkl') def _readData(self): smis=[] clogs=[] mrs=[] for line in file(self.fName,'r').xreadlines(): if len(line) and line[0] != '#': splitL = line.split(',') if len(splitL)==3: smi,clog,mr=splitL smis.append(smi) clogs.append(float(clog)) mrs.append(float(mr)) self.smis = smis self.clogs = clogs self.mrs = mrs def testLogP(self): self._readData() nMols = len(self.smis) #outF = file(self.fName,'w') for i in range(nMols): smi = self.smis[i] mol = Chem.MolFromSmiles(smi) if 1: clog = self.clogs[i] tmp = Crippen.MolLogP(mol) self.failUnless(feq(clog,tmp),'bad logp for %s: %4.4f != %4.4f'%(smi,clog,tmp)) mr = self.mrs[i] tmp = Crippen.MolMR(mol) self.failUnless(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) else: clog = Crippen.MolLogP(mol) mr = Crippen.MolMR(mol) print >>outF,'%s,%.4f,%.4f'%(smi,clog,mr) def testRepeat(self): self._readData() nMols = len(self.smis) for i in range(nMols): smi = self.smis[i] mol = Chem.MolFromSmiles(smi) clog = self.clogs[i] tmp = Crippen.MolLogP(mol) tmp = Crippen.MolLogP(mol) self.failUnless(feq(clog,tmp),'bad logp fooutF,r %s: %4.4f != %4.4f'%(smi,clog,tmp)) mr = self.mrs[i] tmp = Crippen.MolMR(mol) tmp = Crippen.MolMR(mol) self.failUnless(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) def _writeDetailFile(self,inF,outF): while 1: try: smi,refContribs = cPickle.load(inF) except EOFError: break else: try: mol = Chem.MolFromSmiles(smi) except: import traceback traceback.print_exc() mol = None if mol: mol=Chem.AddHs(mol,1) smi2 = Chem.MolToSmiles(mol) contribs = Crippen._GetAtomContribs(mol) cPickle.dump((smi,contribs),outF) else: print 'Problems with SMILES:',smi def _doDetailFile(self,inF,nFailsAllowed=1): done = 0 verbose=0 nFails=0 while not done: if verbose: print '---------------' try: smi,refContribs = cPickle.load(inF) except EOFError: done = 1 else: refContribs = [x[0] for x in refContribs] refOrder= numpy.argsort(refContribs) try: mol = Chem.MolFromSmiles(smi) except: import traceback traceback.print_exc() mol = None if mol: mol=Chem.AddHs(mol,1) smi2 = Chem.MolToSmiles(mol) contribs = Crippen._GetAtomContribs(mol) contribs = [x[0] for x in contribs] # # we're comparing to the old results using the oelib code. # Since we have some disagreements with them as to what is # aromatic and what isn't, we may have different numbers of # Hs. For the sake of comparison, just pop those off our # new results. # while len(contribs)>len(refContribs): del contribs[-1] order = numpy.argsort(contribs) for i in range(len(refContribs)): refL = refContribs[refOrder[i]] l = contribs[order[i]] if not feq(refL,l): print '%s (%s): %d %6.5f != %6.5f'%(smi,smi2,order[i],refL,l) Crippen._GetAtomContribs(mol,force=1) print '-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*' nFails +=1 break; self.failUnless(nFails<nFailsAllowed) else: print 'Problems with SMILES:',smi def testDetails(self): Crippen._Init() inF = open(self.detailName,'rb') if 0: outF = open('tmp.pkl','wb+') self._writeDetailFile(inF,outF) self._doDetailFile(inF) def testDetails2(self): Crippen._Init() inF = open(self.detailName2,'rb') if 0: outF = open('tmp.pkl','wb+') self._writeDetailFile(inF,outF) self._doDetailFile(inF) def testIssue80(self): from rdkit.Chem import Lipinski m = Chem.MolFromSmiles('CCOC') ref = Crippen.MolLogP(m) Lipinski.NHOHCount(m) probe = Crippen.MolLogP(m) self.failUnless(probe==ref) def testIssue1749494(self): m1 = Chem.MolFromSmiles('[*]CC') v = Crippen.MolLogP(m1) self.failUnless(feq(v,0.9739)) if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/UnitTestCrippen.py", "copies": "1", "size": "5412", "license": "bsd-3-clause", "hash": -7279360445538304000, "line_mean": 28.4130434783, "line_max": 101, "alpha_frac": 0.5731707317, "autogenerated": false, "ratio": 2.9096774193548387, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8774836986003293, "avg_score": 0.041602233010309166, "num_lines": 184 }
""" Various bits and pieces for calculating Molecular descriptors """ from rdkit import RDConfig from rdkit.ML.Descriptors import Descriptors from rdkit.Chem import Descriptors as DescriptorsMod from rdkit.RDLogger import logger logger = logger() import re class MolecularDescriptorCalculator(Descriptors.DescriptorCalculator): """ used for calculating descriptors for molecules """ def __init__(self,simpleList,*args,**kwargs): """ Constructor **Arguments** - simpleList: list of simple descriptors to be calculated (see below for format) **Note** - format of simpleList: a list of strings which are functions in the rdkit.Chem.Descriptors module """ self.simpleList = tuple(simpleList) self.descriptorNames = tuple(self.simpleList) self.compoundList = None self._findVersions() def _findVersions(self): """ returns a tuple of the versions of the descriptor calculators """ self.descriptorVersions=[] for nm in self.simpleList: vers='N/A' if hasattr(DescriptorsMod,nm): fn = getattr(DescriptorsMod,nm) if hasattr(fn,'version'): vers = fn.version self.descriptorVersions.append(vers) def SaveState(self,fileName): """ Writes this calculator off to a file so that it can be easily loaded later **Arguments** - fileName: the name of the file to be written """ from rdkit.six.moves import cPickle try: f = open(fileName,'wb+') except Exception: logger.error('cannot open output file %s for writing'%(fileName)) return cPickle.dump(self,f) f.close() def CalcDescriptors(self,mol,*args,**kwargs): """ calculates all descriptors for a given molecule **Arguments** - mol: the molecule to be used **Returns** a tuple of all descriptor values """ res = [-666]*len(self.simpleList) for i,nm in enumerate(self.simpleList): fn = getattr(DescriptorsMod,nm,lambda x:777) try: res[i] = fn(mol) except Exception: import traceback traceback.print_exc() return tuple(res) def GetDescriptorNames(self): """ returns a tuple of the names of the descriptors this calculator generates """ return self.descriptorNames def GetDescriptorSummaries(self): """ returns a tuple of summaries for the descriptors this calculator generates """ res = [] for nm in self.simpleList: fn = getattr(DescriptorsMod,nm,lambda x:777) if hasattr(fn,'__doc__') and fn.__doc__: doc = fn.__doc__.split('\n\n')[0].strip() doc = re.sub('\ *\n\ *',' ',doc) else: doc = 'N/A' res.append(doc) return res def GetDescriptorFuncs(self): """ returns a tuple of the functions used to generate this calculator's descriptors """ res = [] for nm in self.simpleList: fn = getattr(DescriptorsMod,nm,lambda x:777) res.append(fn) return tuple(res) def GetDescriptorVersions(self): """ returns a tuple of the versions of the descriptor calculators """ return tuple(self.descriptorVersions)
{ "repo_name": "adalke/rdkit", "path": "rdkit/ML/Descriptors/MoleculeDescriptors.py", "copies": "1", "size": "3288", "license": "bsd-3-clause", "hash": -5783084161208523000, "line_mean": 24.8897637795, "line_max": 87, "alpha_frac": 0.6435523114, "autogenerated": false, "ratio": 4.054254007398273, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.02212604505208509, "num_lines": 127 }
""" Various bits and pieces for calculating Molecular descriptors """ import re from rdkit.Chem import Descriptors as DescriptorsMod from rdkit.ML.Descriptors import Descriptors from rdkit.RDLogger import logger from rdkit.six.moves import cPickle logger = logger() class MolecularDescriptorCalculator(Descriptors.DescriptorCalculator): """ used for calculating descriptors for molecules """ def __init__(self, simpleList, *args, **kwargs): """ Constructor **Arguments** - simpleList: list of simple descriptors to be calculated (see below for format) **Note** - format of simpleList: a list of strings which are functions in the rdkit.Chem.Descriptors module """ self.simpleList = tuple(simpleList) self.descriptorNames = tuple(self.simpleList) self.compoundList = None self._findVersions() def _findVersions(self): """ returns a tuple of the versions of the descriptor calculators """ self.descriptorVersions = [] for nm in self.simpleList: vers = 'N/A' if hasattr(DescriptorsMod, nm): fn = getattr(DescriptorsMod, nm) if hasattr(fn, 'version'): vers = fn.version self.descriptorVersions.append(vers) def SaveState(self, fileName): """ Writes this calculator off to a file so that it can be easily loaded later **Arguments** - fileName: the name of the file to be written """ try: f = open(fileName, 'wb+') except Exception: logger.error('cannot open output file %s for writing' % (fileName)) return cPickle.dump(self, f) f.close() def CalcDescriptors(self, mol, *args, **kwargs): """ calculates all descriptors for a given molecule **Arguments** - mol: the molecule to be used **Returns** a tuple of all descriptor values """ res = [-666] * len(self.simpleList) for i, nm in enumerate(self.simpleList): fn = getattr(DescriptorsMod, nm, lambda x: 777) try: res[i] = fn(mol) except Exception: import traceback traceback.print_exc() return tuple(res) def GetDescriptorNames(self): """ returns a tuple of the names of the descriptors this calculator generates """ return self.descriptorNames def GetDescriptorSummaries(self): """ returns a tuple of summaries for the descriptors this calculator generates """ res = [] for nm in self.simpleList: fn = getattr(DescriptorsMod, nm, lambda x: 777) if hasattr(fn, '__doc__') and fn.__doc__: doc = fn.__doc__.split('\n\n')[0].strip() doc = re.sub('\ *\n\ *', ' ', doc) else: doc = 'N/A' res.append(doc) return res def GetDescriptorFuncs(self): """ returns a tuple of the functions used to generate this calculator's descriptors """ res = [] for nm in self.simpleList: fn = getattr(DescriptorsMod, nm, lambda x: 777) res.append(fn) return tuple(res) def GetDescriptorVersions(self): """ returns a tuple of the versions of the descriptor calculators """ return tuple(self.descriptorVersions)
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/Descriptors/MoleculeDescriptors.py", "copies": "4", "size": "3269", "license": "bsd-3-clause", "hash": -7746755550722521000, "line_mean": 24.3410852713, "line_max": 87, "alpha_frac": 0.6402569593, "autogenerated": false, "ratio": 4.0110429447852765, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6651299904085276, "avg_score": null, "num_lines": null }
""" functions to match a bunch of fragment descriptors from a file No user-servicable parts inside. ;-) """ import os from rdkit import RDConfig from rdkit import Chem defaultPatternFileName = os.path.join(RDConfig.RDDataDir, 'FragmentDescriptors.csv') def _CountMatches(mol, patt, unique=True): return len(mol.GetSubstructMatches(patt, uniquify=unique)) fns = [] def _LoadPatterns(fileName=None): if fileName is None: fileName = defaultPatternFileName try: with open(fileName, 'r') as inF: for line in inF.readlines(): if len(line) and line[0] != '#': splitL = line.split('\t') if len(splitL) >= 3: name = splitL[0] descr = splitL[1] sma = splitL[2] descr = descr.replace('"', '') patt = Chem.MolFromSmarts(sma) if not patt or patt.GetNumAtoms() == 0: raise ImportError('Smarts %s could not be parsed' % (repr(sma))) fn = lambda mol, countUnique=True, pattern=patt: _CountMatches(mol, pattern, unique=countUnique) fn.__doc__ = descr name = name.replace('=', '_') name = name.replace('-', '_') fns.append((name, fn)) except IOError: pass _LoadPatterns() for name, fn in fns: exec('%s=fn' % (name)) fn = None
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/Fragments.py", "copies": "12", "size": "1619", "license": "bsd-3-clause", "hash": 4765826143733054000, "line_mean": 26.9137931034, "line_max": 108, "alpha_frac": 0.6145768993, "autogenerated": false, "ratio": 3.4156118143459917, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
""" functions to match a bunch of fragment descriptors from a file No user-servicable parts inside. ;-) """ import os from rdkit import RDConfig from rdkit import Chem defaultPatternFileName = os.path.join(RDConfig.RDDataDir,'FragmentDescriptors.csv') def _CountMatches(mol,patt,unique=True): return len(mol.GetSubstructMatches(patt,uniquify=unique)) fns = [] def _LoadPatterns(fileName=None): if fileName is None: fileName = defaultPatternFileName try: inF = open(fileName,'r') except IOError: pass else: for line in inF.readlines(): if len(line) and line[0] != '#': splitL = line.split('\t') if len(splitL)>=3: name = splitL[0] descr = splitL[1] sma = splitL[2] descr=descr.replace('"','') ok=1 try: patt = Chem.MolFromSmarts(sma) except: ok=0 else: if not patt or patt.GetNumAtoms()==0: ok=0 if not ok: raise ImportError,'Smarts %s could not be parsed'%(repr(sma)) fn = lambda mol,countUnique=True,pattern=patt:_CountMatches(mol,pattern,unique=countUnique) fn.__doc__ = descr name = name.replace('=','_') name = name.replace('-','_') fns.append((name,fn)) _LoadPatterns() for name,fn in fns: exec('%s=fn'%(name)) fn=None
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Fragments.py", "copies": "2", "size": "1676", "license": "bsd-3-clause", "hash": 6653921213621684000, "line_mean": 26.4754098361, "line_max": 101, "alpha_frac": 0.6097852029, "autogenerated": false, "ratio": 3.3927125506072873, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5002497753507287, "avg_score": null, "num_lines": null }
""" This is a rough coverage test of the python wrapper it's intended to be shallow, but broad """ import unittest,os from rdkit.six.moves import cPickle from rdkit import RDConfig from rdkit.RDLogger import logger logger=logger() from rdkit import Chem from rdkit.Chem import FragmentCatalog from rdkit import DataStructs class TestCase(unittest.TestCase): def setUp(self) : self.fName=os.path.join(RDConfig.RDBaseDir,'Code','GraphMol', 'FragCatalog','test_data','funcGroups.txt') self.smiName=os.path.join(RDConfig.RDBaseDir,'Code','GraphMol', 'FragCatalog','test_data','mols.smi') def test0Params(self) : fparams = FragmentCatalog.FragCatParams(1, 6, self.fName, 1.0e-8) ctype = fparams.GetTypeString() assert(ctype == "Fragment Catalog Parameters") assert(fparams.GetLowerFragLength() == 1) assert(fparams.GetUpperFragLength() == 6) ngps = fparams.GetNumFuncGroups() assert ngps==15 for i in range(ngps) : mol = fparams.GetFuncGroup(i) def test1Catalog(self) : fparams = FragmentCatalog.FragCatParams(1, 6, self.fName, 1.0e-8) fcat = FragmentCatalog.FragCatalog(fparams) assert(fcat.GetNumEntries() == 0) assert( fcat.GetFPLength() == 0) nparams = fcat.GetCatalogParams() assert(nparams.GetLowerFragLength() == 1) assert(nparams.GetUpperFragLength() == 6) def test2Generator(self) : fparams = FragmentCatalog.FragCatParams(1, 6, self.fName, 1.0e-8) fcat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() suppl = Chem.SmilesMolSupplier(self.smiName," ",0,1,0) for mol in suppl: nent = fgen.AddFragsFromMol(mol, fcat) assert fcat.GetNumEntries()==21 assert fcat.GetFPLength()==21 for id in range(fcat.GetNumEntries()): assert fcat.GetEntryBitId(id)==id assert fcat.GetEntryOrder(id)==fcat.GetBitOrder(id) assert fcat.GetEntryDescription(id)==fcat.GetBitDescription(id) assert tuple(fcat.GetEntryFuncGroupIds(id))==tuple(fcat.GetBitFuncGroupIds(id)) def test3FPgenerator(self) : with open(self.smiName,'r') as smiF: smiLines = smiF.readlines() fparams = FragmentCatalog.FragCatParams(1, 6, self.fName) fcat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() suppl = Chem.SmilesMolSupplier(self.smiName," ",0,1,0) smiles = [] for mol in suppl: nent = fgen.AddFragsFromMol(mol, fcat) smiles.append(Chem.MolToSmiles(mol)) assert fcat.GetNumEntries()==21 assert fcat.GetFPLength()==21,fcat.GetFPLength() fpgen = FragmentCatalog.FragFPGenerator() obits = [3,2,3,3,2,3,5,5,5,4,5,6] obls = [(0,1,2),(1,3),(1,4,5),(1,6,7),(0,8),(0,6,9),(0,1,2,3,10), (0,1,2,8,11),(1,3,4,5,12),(1,4,5,13),(1,3,6,7,14),(0,1,6,7,9,15)] for i in range(len(smiles)): smi = smiles[i] mol = Chem.MolFromSmiles(smi) fp = fpgen.GetFPForMol(mol, fcat) if i < len(obits): assert fp.GetNumOnBits()==obits[i],'%s: %s'%(smi,str(fp.GetOnBits())) obl = fp.GetOnBits() if i < len(obls): assert tuple(obl)==obls[i],'%s: %s'%(smi,obl) def test4Serialize(self) : with open(self.smiName,'r') as smiF: smiLines = smiF.readlines() fparams = FragmentCatalog.FragCatParams(1, 6, self.fName) fcat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() suppl = Chem.SmilesMolSupplier(self.smiName," ",0,1,0) smiles = [] for mol in suppl: nent = fgen.AddFragsFromMol(mol, fcat) smiles.append(Chem.MolToSmiles(mol)) assert fcat.GetNumEntries()==21 assert fcat.GetFPLength()==21,fcat.GetFPLength() pkl = cPickle.dumps(fcat) fcat2 = cPickle.loads(pkl) assert fcat2.GetNumEntries()==21 assert fcat2.GetFPLength()==21,fcat2.GetFPLength() fpgen = FragmentCatalog.FragFPGenerator() for i in range(len(smiles)): smi = smiles[i] mol = Chem.MolFromSmiles(smi) fp1 = fpgen.GetFPForMol(mol, fcat) fp2 = fpgen.GetFPForMol(mol, fcat2) assert fp1.GetNumOnBits()==fp2.GetNumOnBits() obl1 = fp1.GetOnBits() obl2 = fp2.GetOnBits() assert tuple(obl1)==tuple(obl2) def test5FPsize(self) : with open(self.smiName,'r') as smiF: smiLines = smiF.readlines() fparams = FragmentCatalog.FragCatParams(6, 6, self.fName) fcat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() suppl = [Chem.MolFromSmiles('C1CCCOC1O')] for mol in suppl: nent = fgen.AddFragsFromMol(mol, fcat) assert fcat.GetFPLength()==1 for i in range(fcat.GetFPLength()): assert fcat.GetBitOrder(i)==6 assert fcat.GetBitDescription(i)=="C1CCOC<-O>C1",fcat.GetBitDescription(i) assert tuple(fcat.GetBitFuncGroupIds(i))==(1,) def test6DownEntries(self) : fparams = FragmentCatalog.FragCatParams(1, 6, self.fName, 1.0e-8) fcat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() suppl = Chem.SmilesMolSupplier(self.smiName," ",0,1,0) for mol in suppl: nent = fgen.AddFragsFromMol(mol, fcat) assert fcat.GetNumEntries()==21 assert fcat.GetFPLength()==21 assert tuple(fcat.GetEntryDownIds(0))==(2,8,9,16) assert tuple(fcat.GetEntryDownIds(1))==(2,3,5,7) def test7Issue116(self): smiList = ['Cc1ccccc1'] suppl = Chem.SmilesMolSupplierFromText('\n'.join(smiList), ',',0,-1,0) fparams = FragmentCatalog.FragCatParams(2, 2, self.fName, 1.0e-8) cat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() for mol in suppl: nent = fgen.AddFragsFromMol(mol, cat) assert cat.GetFPLength()==2 assert cat.GetBitDescription(0)=='ccC' fpgen = FragmentCatalog.FragFPGenerator() mol = Chem.MolFromSmiles('Cc1ccccc1') fp = fpgen.GetFPForMol(mol,cat) assert fp[0] assert fp[1] mol = Chem.MolFromSmiles('c1ccccc1-c1ccccc1') fp = fpgen.GetFPForMol(mol,cat) assert not fp[0] assert fp[1] def test8Issue118(self): smiList = ['CCN(C(N)=O)N=O'] fName=os.path.join(RDConfig.RDDataDir,'FunctionalGroups.txt') suppl = Chem.SmilesMolSupplierFromText('\n'.join(smiList), ',',0,-1,0) fparams = FragmentCatalog.FragCatParams(2, 4, fName, 1.0e-8) cat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() for mol in suppl: nent = fgen.AddFragsFromMol(mol, cat) assert cat.GetFPLength()==1 assert cat.GetBitDescription(0)=='CCN(<-C(=O)N>)<-N=O>' if __name__ == '__main__': unittest.main()
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "Code/GraphMol/FragCatalog/Wrap/rough_test.py", "copies": "1", "size": "7613", "license": "bsd-3-clause", "hash": -6086574800378182000, "line_mean": 39.2804232804, "line_max": 91, "alpha_frac": 0.5931958492, "autogenerated": false, "ratio": 3.097233523189585, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9083298351650049, "avg_score": 0.02142620414790747, "num_lines": 189 }
""" Calculation of topological/topochemical descriptors. """ from __future__ import print_function from rdkit import Chem from rdkit.Chem import Graphs from rdkit.Chem import rdchem from rdkit.Chem import rdMolDescriptors # FIX: remove this dependency here and below from rdkit.Chem import pyPeriodicTable as PeriodicTable import numpy import math from rdkit.ML.InfoTheory import entropy periodicTable = rdchem.GetPeriodicTable() _log2val = math.log(2) def _log2(x): return math.log(x) / _log2val def _VertexDegrees(mat, onlyOnes=0): """ *Internal Use Only* this is just a row sum of the matrix... simple, neh? """ if not onlyOnes: res = sum(mat) else: res = sum(numpy.equal(mat, 1)) return res def _NumAdjacencies(mol, dMat): """ *Internal Use Only* """ res = mol.GetNumBonds() return res def _GetCountDict(arr): """ *Internal Use Only* """ res = {} for v in arr: res[v] = res.get(v, 0) + 1 return res def _pyHallKierAlpha(m): """ calculate the Hall-Kier alpha value for a molecule From equations (58) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ alphaSum = 0.0 rC = PeriodicTable.nameTable['C'][5] for atom in m.GetAtoms(): atNum = atom.GetAtomicNum() if not atNum: continue symb = atom.GetSymbol() alphaV = PeriodicTable.hallKierAlphas.get(symb, None) if alphaV is not None: hyb = atom.GetHybridization() - 2 if (hyb < len(alphaV)): alpha = alphaV[hyb] if alpha is None: alpha = alphaV[-1] else: alpha = alphaV[-1] else: rA = PeriodicTable.nameTable[symb][5] alpha = rA / rC - 1 print(atom.GetIdx(), atom.GetSymbol(), alpha) alphaSum += alpha return alphaSum #HallKierAlpha.version="1.0.2" def Ipc(mol, avg=0, dMat=None, forceDMat=0): """This returns the information content of the coefficients of the characteristic polynomial of the adjacency matrix of a hydrogen-suppressed graph of a molecule. 'avg = 1' returns the information content divided by the total population. From D. Bonchev & N. Trinajstic, J. Chem. Phys. vol 67, 4517-4533 (1977) """ if forceDMat or dMat is None: if forceDMat: dMat = Chem.GetDistanceMatrix(mol, 0) mol._adjMat = dMat else: try: dMat = mol._adjMat except AttributeError: dMat = Chem.GetDistanceMatrix(mol, 0) mol._adjMat = dMat adjMat = numpy.equal(dMat, 1) cPoly = abs(Graphs.CharacteristicPolynomial(mol, adjMat)) if avg: return entropy.InfoEntropy(cPoly) else: return sum(cPoly) * entropy.InfoEntropy(cPoly) Ipc.version = "1.0.0" def _pyKappa1(mol): """ Hall-Kier Kappa1 value From equations (58) and (59) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ P1 = mol.GetNumBonds(1) A = mol.GetNumHeavyAtoms() alpha = HallKierAlpha(mol) denom = P1 + alpha if denom: kappa = (A + alpha) * (A + alpha - 1)**2 / denom**2 else: kappa = 0.0 return kappa #Kappa1.version="1.0.0" def _pyKappa2(mol): """ Hall-Kier Kappa2 value From equations (58) and (60) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ P2 = len(Chem.FindAllPathsOfLengthN(mol, 2)) A = mol.GetNumHeavyAtoms() alpha = HallKierAlpha(mol) denom = (P2 + alpha)**2 if denom: kappa = (A + alpha - 1) * (A + alpha - 2)**2 / denom else: kappa = 0 return kappa #Kappa2.version="1.0.0" def _pyKappa3(mol): """ Hall-Kier Kappa3 value From equations (58), (61) and (62) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ P3 = len(Chem.FindAllPathsOfLengthN(mol, 3)) A = mol.GetNumHeavyAtoms() alpha = HallKierAlpha(mol) denom = (P3 + alpha)**2 if denom: if A % 2 == 1: kappa = (A + alpha - 1) * (A + alpha - 3)**2 / denom else: kappa = (A + alpha - 2) * (A + alpha - 3)**2 / denom else: kappa = 0 return kappa #Kappa3.version="1.0.0" HallKierAlpha = lambda x: rdMolDescriptors.CalcHallKierAlpha(x) HallKierAlpha.version = rdMolDescriptors._CalcHallKierAlpha_version Kappa1 = lambda x: rdMolDescriptors.CalcKappa1(x) Kappa1.version = rdMolDescriptors._CalcKappa1_version Kappa2 = lambda x: rdMolDescriptors.CalcKappa2(x) Kappa2.version = rdMolDescriptors._CalcKappa2_version Kappa3 = lambda x: rdMolDescriptors.CalcKappa3(x) Kappa3.version = rdMolDescriptors._CalcKappa3_version def Chi0(mol): """ From equations (1),(9) and (10) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ deltas = [x.GetDegree() for x in mol.GetAtoms()] while 0 in deltas: deltas.remove(0) deltas = numpy.array(deltas, 'd') res = sum(numpy.sqrt(1. / deltas)) return res Chi0.version = "1.0.0" def Chi1(mol): """ From equations (1),(11) and (12) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ c1s = [x.GetBeginAtom().GetDegree() * x.GetEndAtom().GetDegree() for x in mol.GetBonds()] while 0 in c1s: c1s.remove(0) c1s = numpy.array(c1s, 'd') res = sum(numpy.sqrt(1. / c1s)) return res Chi1.version = "1.0.0" def _nVal(atom): return periodicTable.GetNOuterElecs(atom.GetAtomicNum()) - atom.GetTotalNumHs() def _hkDeltas(mol, skipHs=1): global periodicTable res = [] if hasattr(mol, '_hkDeltas') and mol._hkDeltas is not None: return mol._hkDeltas for atom in mol.GetAtoms(): n = atom.GetAtomicNum() if n > 1: nV = periodicTable.GetNOuterElecs(n) nHs = atom.GetTotalNumHs() if n <= 10: # first row res.append(float(nV - nHs)) else: # second row and up res.append(float(nV - nHs) / float(n - nV - 1)) elif n == 1: if not skipHs: res.append(0.0) else: res.append(0.0) mol._hkDeltas = res return res def _pyChi0v(mol): """ From equations (5),(9) and (10) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ deltas = _hkDeltas(mol) while 0 in deltas: deltas.remove(0) mol._hkDeltas = None res = sum(numpy.sqrt(1. / numpy.array(deltas))) return res def _pyChi1v(mol): """ From equations (5),(11) and (12) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ deltas = numpy.array(_hkDeltas(mol, skipHs=0)) res = 0.0 for bond in mol.GetBonds(): v = deltas[bond.GetBeginAtomIdx()] * deltas[bond.GetEndAtomIdx()] if v != 0.0: res += numpy.sqrt(1. / v) return res def _pyChiNv_(mol, order=2): """ From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991) **NOTE**: because the current path finding code does, by design, detect rings as paths (e.g. in C1CC1 there is *1* atom path of length 3), values of ChiNv with N >= 3 may give results that differ from those provided by the old code in molecules that have rings of size 3. """ deltas = numpy.array( [(1. / numpy.sqrt(hkd) if hkd != 0.0 else 0.0) for hkd in _hkDeltas(mol, skipHs=0)]) accum = 0.0 for path in Chem.FindAllPathsOfLengthN(mol, order + 1, useBonds=0): accum += numpy.prod(deltas[numpy.array(path)]) return accum def _pyChi2v(mol): """ From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ return _pyChiNv_(mol, 2) def _pyChi3v(mol): """ From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ return _pyChiNv_(mol, 3) def _pyChi4v(mol): """ From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991) **NOTE**: because the current path finding code does, by design, detect rings as paths (e.g. in C1CC1 there is *1* atom path of length 3), values of Chi4v may give results that differ from those provided by the old code in molecules that have 3 rings. """ return _pyChiNv_(mol, 4) def _pyChi0n(mol): """ Similar to Hall Kier Chi0v, but uses nVal instead of valence This makes a big difference after we get out of the first row. """ deltas = [_nVal(x) for x in mol.GetAtoms()] while deltas.count(0): deltas.remove(0) deltas = numpy.array(deltas, 'd') res = sum(numpy.sqrt(1. / deltas)) return res def _pyChi1n(mol): """ Similar to Hall Kier Chi1v, but uses nVal instead of valence """ delts = numpy.array([_nVal(x) for x in mol.GetAtoms()], 'd') res = 0.0 for bond in mol.GetBonds(): v = delts[bond.GetBeginAtomIdx()] * delts[bond.GetEndAtomIdx()] if v != 0.0: res += numpy.sqrt(1. / v) return res def _pyChiNn_(mol, order=2): """ Similar to Hall Kier ChiNv, but uses nVal instead of valence This makes a big difference after we get out of the first row. **NOTE**: because the current path finding code does, by design, detect rings as paths (e.g. in C1CC1 there is *1* atom path of length 3), values of ChiNn with N >= 3 may give results that differ from those provided by the old code in molecules that have rings of size 3. """ nval = [_nVal(x) for x in mol.GetAtoms()] deltas = numpy.array([(1. / numpy.sqrt(x) if x else 0.0) for x in nval]) accum = 0.0 for path in Chem.FindAllPathsOfLengthN(mol, order + 1, useBonds=0): accum += numpy.prod(deltas[numpy.array(path)]) return accum def _pyChi2n(mol): """ Similar to Hall Kier Chi2v, but uses nVal instead of valence This makes a big difference after we get out of the first row. """ return _pyChiNn_(mol, 2) def _pyChi3n(mol): """ Similar to Hall Kier Chi3v, but uses nVal instead of valence This makes a big difference after we get out of the first row. """ return _pyChiNn_(mol, 3) def _pyChi4n(mol): """ Similar to Hall Kier Chi4v, but uses nVal instead of valence This makes a big difference after we get out of the first row. **NOTE**: because the current path finding code does, by design, detect rings as paths (e.g. in C1CC1 there is *1* atom path of length 3), values of Chi4n may give results that differ from those provided by the old code in molecules that have 3 rings. """ return _pyChiNn_(mol, 4) Chi0v = lambda x: rdMolDescriptors.CalcChi0v(x) Chi0v.version = rdMolDescriptors._CalcChi0v_version Chi1v = lambda x: rdMolDescriptors.CalcChi1v(x) Chi1v.version = rdMolDescriptors._CalcChi1v_version Chi2v = lambda x: rdMolDescriptors.CalcChi2v(x) Chi2v.version = rdMolDescriptors._CalcChi2v_version Chi3v = lambda x: rdMolDescriptors.CalcChi3v(x) Chi3v.version = rdMolDescriptors._CalcChi3v_version Chi4v = lambda x: rdMolDescriptors.CalcChi4v(x) Chi4v.version = rdMolDescriptors._CalcChi4v_version ChiNv_ = lambda x, y: rdMolDescriptors.CalcChiNv(x, y) ChiNv_.version = rdMolDescriptors._CalcChiNv_version Chi0n = lambda x: rdMolDescriptors.CalcChi0n(x) Chi0n.version = rdMolDescriptors._CalcChi0n_version Chi1n = lambda x: rdMolDescriptors.CalcChi1n(x) Chi1n.version = rdMolDescriptors._CalcChi1n_version Chi2n = lambda x: rdMolDescriptors.CalcChi2n(x) Chi2n.version = rdMolDescriptors._CalcChi2n_version Chi3n = lambda x: rdMolDescriptors.CalcChi3n(x) Chi3n.version = rdMolDescriptors._CalcChi3n_version Chi4n = lambda x: rdMolDescriptors.CalcChi4n(x) Chi4n.version = rdMolDescriptors._CalcChi4n_version ChiNn_ = lambda x, y: rdMolDescriptors.CalcChiNn(x, y) ChiNn_.version = rdMolDescriptors._CalcChiNn_version def BalabanJ(mol, dMat=None, forceDMat=0): """ Calculate Balaban's J value for a molecule **Arguments** - mol: a molecule - dMat: (optional) a distance/adjacency matrix for the molecule, if this is not provide, one will be calculated - forceDMat: (optional) if this is set, the distance/adjacency matrix will be recalculated regardless of whether or not _dMat_ is provided or the molecule already has one **Returns** - a float containing the J value We follow the notation of Balaban's paper: Chem. Phys. Lett. vol 89, 399-404, (1982) """ # if no dMat is passed in, calculate one ourselves if forceDMat or dMat is None: if forceDMat: # FIX: should we be using atom weights here or not? dMat = Chem.GetDistanceMatrix(mol, useBO=1, useAtomWts=0, force=1) mol._balabanMat = dMat adjMat = Chem.GetAdjacencyMatrix(mol, useBO=0, emptyVal=0, force=0, prefix="NoBO") mol._adjMat = adjMat else: try: # first check if the molecule already has one dMat = mol._balabanMat except AttributeError: # nope, gotta calculate one dMat = Chem.GetDistanceMatrix(mol, useBO=1, useAtomWts=0, force=0, prefix="Balaban") # now store it mol._balabanMat = dMat try: adjMat = mol._adjMat except AttributeError: adjMat = Chem.GetAdjacencyMatrix(mol, useBO=0, emptyVal=0, force=0, prefix="NoBO") mol._adjMat = adjMat else: adjMat = Chem.GetAdjacencyMatrix(mol, useBO=0, emptyVal=0, force=0, prefix="NoBO") s = _VertexDegrees(dMat) q = _NumAdjacencies(mol, dMat) n = mol.GetNumAtoms() mu = q - n + 1 sum = 0. nS = len(s) for i in range(nS): si = s[i] for j in range(i, nS): if adjMat[i, j] == 1: sum += 1. / numpy.sqrt(si * s[j]) if mu + 1 != 0: J = float(q) / float(mu + 1) * sum else: J = 0 return J BalabanJ.version = "1.0.0" #------------------------------------------------------------------------ # # Start block of BertzCT stuff. # def _AssignSymmetryClasses(mol, vdList, bdMat, forceBDMat, numAtoms, cutoff): """ Used by BertzCT vdList: the number of neighbors each atom has bdMat: "balaban" distance matrix """ if forceBDMat: bdMat = Chem.GetDistanceMatrix(mol, useBO=1, useAtomWts=0, force=1, prefix="Balaban") mol._balabanMat = bdMat atomIdx = 0 keysSeen = [] symList = [0] * numAtoms for i in range(numAtoms): tmpList = bdMat[i].tolist() tmpList.sort() theKey = tuple(['%.4f' % x for x in tmpList[:cutoff]]) try: idx = keysSeen.index(theKey) except ValueError: idx = len(keysSeen) keysSeen.append(theKey) symList[i] = idx + 1 return tuple(symList) def _LookUpBondOrder(atom1Id, atom2Id, bondDic): """ Used by BertzCT """ if atom1Id < atom2Id: theKey = (atom1Id, atom2Id) else: theKey = (atom2Id, atom1Id) tmp = bondDic[theKey] if tmp == Chem.BondType.AROMATIC: tmp = 1.5 else: tmp = float(tmp) #tmp = int(tmp) return tmp def _CalculateEntropies(connectionDict, atomTypeDict, numAtoms): """ Used by BertzCT """ connectionList = list(connectionDict.values()) totConnections = sum(connectionList) connectionIE = totConnections * ( entropy.InfoEntropy(numpy.array(connectionList)) + math.log(totConnections) / _log2val) atomTypeList = list(atomTypeDict.values()) atomTypeIE = numAtoms * entropy.InfoEntropy(numpy.array(atomTypeList)) return atomTypeIE + connectionIE def _CreateBondDictEtc(mol, numAtoms): """ _Internal Use Only_ Used by BertzCT """ bondDict = {} nList = [None] * numAtoms vdList = [0] * numAtoms for aBond in mol.GetBonds(): atom1 = aBond.GetBeginAtomIdx() atom2 = aBond.GetEndAtomIdx() if atom1 > atom2: atom2, atom1 = atom1, atom2 if not aBond.GetIsAromatic(): bondDict[(atom1, atom2)] = aBond.GetBondType() else: # mark Kekulized systems as aromatic bondDict[(atom1, atom2)] = Chem.BondType.AROMATIC if nList[atom1] is None: nList[atom1] = [atom2] elif atom2 not in nList[atom1]: nList[atom1].append(atom2) if nList[atom2] is None: nList[atom2] = [atom1] elif atom1 not in nList[atom2]: nList[atom2].append(atom1) for i, element in enumerate(nList): try: element.sort() vdList[i] = len(element) except Exception: vdList[i] = 0 return bondDict, nList, vdList def BertzCT(mol, cutoff=100, dMat=None, forceDMat=1): """ A topological index meant to quantify "complexity" of molecules. Consists of a sum of two terms, one representing the complexity of the bonding, the other representing the complexity of the distribution of heteroatoms. From S. H. Bertz, J. Am. Chem. Soc., vol 103, 3599-3601 (1981) "cutoff" is an integer value used to limit the computational expense. A cutoff value tells the program to consider vertices topologically identical if their distance vectors (sets of distances to all other vertices) are equal out to the "cutoff"th nearest-neighbor. **NOTE** The original implementation had the following comment: > this implementation treats aromatic rings as the > corresponding Kekule structure with alternating bonds, > for purposes of counting "connections". Upon further thought, this is the WRONG thing to do. It results in the possibility of a molecule giving two different CT values depending on the kekulization. For example, in the old implementation, these two SMILES: CC2=CN=C1C3=C(C(C)=C(C=N3)C)C=CC1=C2C CC3=CN=C2C1=NC=C(C)C(C)=C1C=CC2=C3C which correspond to differentk kekule forms, yield different values. The new implementation uses consistent (aromatic) bond orders for aromatic bonds. THIS MEANS THAT THIS IMPLEMENTATION IS NOT BACKWARDS COMPATIBLE. Any molecule containing aromatic rings will yield different values with this implementation. The new behavior is the correct one, so we're going to live with the breakage. **NOTE** this barfs if the molecule contains a second (or nth) fragment that is one atom. """ atomTypeDict = {} connectionDict = {} numAtoms = mol.GetNumAtoms() if forceDMat or dMat is None: if forceDMat: # nope, gotta calculate one dMat = Chem.GetDistanceMatrix(mol, useBO=0, useAtomWts=0, force=1) mol._adjMat = dMat else: try: dMat = mol._adjMat except AttributeError: dMat = Chem.GetDistanceMatrix(mol, useBO=0, useAtomWts=0, force=1) mol._adjMat = dMat if numAtoms < 2: return 0 bondDict, neighborList, vdList = _CreateBondDictEtc(mol, numAtoms) symmetryClasses = _AssignSymmetryClasses(mol, vdList, dMat, forceDMat, numAtoms, cutoff) #print('Symmm Classes:',symmetryClasses) for atomIdx in range(numAtoms): hingeAtomNumber = mol.GetAtomWithIdx(atomIdx).GetAtomicNum() atomTypeDict[hingeAtomNumber] = atomTypeDict.get(hingeAtomNumber, 0) + 1 hingeAtomClass = symmetryClasses[atomIdx] numNeighbors = vdList[atomIdx] for i in range(numNeighbors): neighbor_iIdx = neighborList[atomIdx][i] NiClass = symmetryClasses[neighbor_iIdx] bond_i_order = _LookUpBondOrder(atomIdx, neighbor_iIdx, bondDict) #print('\t',atomIdx,i,hingeAtomClass,NiClass,bond_i_order) if (bond_i_order > 1) and (neighbor_iIdx > atomIdx): numConnections = bond_i_order * (bond_i_order - 1) / 2 connectionKey = (min(hingeAtomClass, NiClass), max(hingeAtomClass, NiClass)) connectionDict[connectionKey] = connectionDict.get(connectionKey, 0) + numConnections for j in range(i + 1, numNeighbors): neighbor_jIdx = neighborList[atomIdx][j] NjClass = symmetryClasses[neighbor_jIdx] bond_j_order = _LookUpBondOrder(atomIdx, neighbor_jIdx, bondDict) numConnections = bond_i_order * bond_j_order connectionKey = (min(NiClass, NjClass), hingeAtomClass, max(NiClass, NjClass)) connectionDict[connectionKey] = connectionDict.get(connectionKey, 0) + numConnections if not connectionDict: connectionDict = {'a': 1} return _CalculateEntropies(connectionDict, atomTypeDict, numAtoms) BertzCT.version = "2.0.0" # Recent Revisions: # 1.0.0 -> 2.0.0: # - force distance matrix updates properly (Fixed as part of Issue 125) # - handle single-atom fragments (Issue 136) # # End block of BertzCT stuff. # #------------------------------------------------------------------------
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/GraphDescriptors.py", "copies": "1", "size": "20134", "license": "bsd-3-clause", "hash": 6451918916735926000, "line_mean": 27.9697841727, "line_max": 93, "alpha_frac": 0.6573954505, "autogenerated": false, "ratio": 2.9867972110962766, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41441926615962765, "avg_score": null, "num_lines": null }
""" Calculation of topological/topochemical descriptors. """ from rdkit import Chem from rdkit.Chem import Graphs from rdkit.Chem import rdchem from rdkit.Chem import rdMolDescriptors # FIX: remove this dependency here and below from rdkit.Chem import pyPeriodicTable as PeriodicTable import numpy import math from rdkit.ML.InfoTheory import entropy periodicTable = rdchem.GetPeriodicTable() _log2val = math.log(2) def _log2(x): return math.log(x) / _log2val def _VertexDegrees(mat,onlyOnes=0): """ *Internal Use Only* this is just a row sum of the matrix... simple, neh? """ if not onlyOnes: res = sum(mat) else: res = sum(numpy.equal(mat,1)) return res def _NumAdjacencies(mol,dMat): """ *Internal Use Only* """ res = mol.GetNumBonds() return res def _GetCountDict(arr): """ *Internal Use Only* """ res = {} for v in arr: res[v] = res.get(v,0)+1 return res def _pyHallKierAlpha(m): """ calculate the Hall-Kier alpha value for a molecule From equations (58) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ alphaSum = 0.0 rC = PeriodicTable.nameTable['C'][5] for atom in m.GetAtoms(): atNum=atom.GetAtomicNum() if not atNum: continue symb = atom.GetSymbol() alphaV = PeriodicTable.hallKierAlphas.get(symb,None) if alphaV is not None: hyb = atom.GetHybridization()-2 if(hyb<len(alphaV)): alpha = alphaV[hyb] if alpha is None: alpha = alphaV[-1] else: alpha = alphaV[-1] else: rA = PeriodicTable.nameTable[symb][5] alpha = rA/rC - 1 print atom.GetIdx(),atom.GetSymbol(),alpha alphaSum += alpha return alphaSum #HallKierAlpha.version="1.0.2" def Ipc(mol, avg = 0, dMat = None, forceDMat = 0): """This returns the information content of the coefficients of the characteristic polynomial of the adjacency matrix of a hydrogen-suppressed graph of a molecule. 'avg = 1' returns the information content divided by the total population. From D. Bonchev & N. Trinajstic, J. Chem. Phys. vol 67, 4517-4533 (1977) """ if forceDMat or dMat is None: if forceDMat: dMat = Chem.GetDistanceMatrix(mol,0) mol._adjMat = dMat else: try: dMat = mol._adjMat except AttributeError: dMat = Chem.GetDistanceMatrix(mol,0) mol._adjMat = dMat adjMat = numpy.equal(dMat,1) cPoly = abs(Graphs.CharacteristicPolynomial(mol, adjMat)) if avg: return entropy.InfoEntropy(cPoly) else: return sum(cPoly)*entropy.InfoEntropy(cPoly) Ipc.version="1.0.0" def _pyKappa1(mol): """ Hall-Kier Kappa1 value From equations (58) and (59) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ P1 = mol.GetNumBonds(1) A = mol.GetNumHeavyAtoms() alpha = HallKierAlpha(mol) denom = P1 + alpha if denom: kappa = (A + alpha)*(A + alpha - 1)**2 / denom**2 else: kappa = 0.0 return kappa #Kappa1.version="1.0.0" def _pyKappa2(mol): """ Hall-Kier Kappa2 value From equations (58) and (60) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ P2 = len(Chem.FindAllPathsOfLengthN(mol,2)) A = mol.GetNumHeavyAtoms() alpha = HallKierAlpha(mol) denom = (P2 + alpha)**2 if denom: kappa = (A + alpha - 1)*(A + alpha - 2)**2 / denom else: kappa = 0 return kappa #Kappa2.version="1.0.0" def _pyKappa3(mol): """ Hall-Kier Kappa3 value From equations (58), (61) and (62) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ P3 = len(Chem.FindAllPathsOfLengthN(mol,3)) A = mol.GetNumHeavyAtoms() alpha = HallKierAlpha(mol) denom = (P3 + alpha)**2 if denom: if A % 2 == 1: kappa = (A + alpha - 1)*(A + alpha - 3)**2 / denom else: kappa = (A + alpha - 2)*(A + alpha - 3)**2 / denom else: kappa = 0 return kappa #Kappa3.version="1.0.0" HallKierAlpha = lambda x:rdMolDescriptors.CalcHallKierAlpha(x) HallKierAlpha.version=rdMolDescriptors._CalcHallKierAlpha_version Kappa1 = lambda x:rdMolDescriptors.CalcKappa1(x) Kappa1.version=rdMolDescriptors._CalcKappa1_version Kappa2 = lambda x:rdMolDescriptors.CalcKappa2(x) Kappa2.version=rdMolDescriptors._CalcKappa2_version Kappa3 = lambda x:rdMolDescriptors.CalcKappa3(x) Kappa3.version=rdMolDescriptors._CalcKappa3_version def Chi0(mol): """ From equations (1),(9) and (10) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ deltas = [x.GetDegree() for x in mol.GetAtoms()] while 0 in deltas: deltas.remove(0) deltas = numpy.array(deltas,'d') res = sum(numpy.sqrt(1./deltas)) return res Chi0.version="1.0.0" def Chi1(mol): """ From equations (1),(11) and (12) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ c1s = [x.GetBeginAtom().GetDegree()*x.GetEndAtom().GetDegree() for x in mol.GetBonds()] while 0 in c1s: c1s.remove(0) c1s = numpy.array(c1s,'d') res = sum(numpy.sqrt(1./c1s)) return res Chi1.version="1.0.0" def _nVal(atom): return periodicTable.GetNOuterElecs(atom.GetAtomicNum())-atom.GetTotalNumHs() def _hkDeltas(mol,skipHs=1): global periodicTable res = [] if hasattr(mol,'_hkDeltas') and mol._hkDeltas is not None: return mol._hkDeltas for atom in mol.GetAtoms(): n = atom.GetAtomicNum() if n>1: nV = periodicTable.GetNOuterElecs(n) nHs = atom.GetTotalNumHs() if n <= 10: # first row res.append(float(nV-nHs)) else: # second row and up res.append(float(nV-nHs)/float(n-nV-1)) elif n==1: if not skipHs: res.append(0.0) else: res.append(0.0) mol._hkDeltas = res return res def _pyChi0v(mol): """ From equations (5),(9) and (10) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ deltas = _hkDeltas(mol) while 0 in deltas: deltas.remove(0) mol._hkDeltas=None res = sum(numpy.sqrt(1./numpy.array(deltas))) return res def _pyChi1v(mol): """ From equations (5),(11) and (12) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ deltas = numpy.array(_hkDeltas(mol,skipHs=0)) res = 0.0 for bond in mol.GetBonds(): v = deltas[bond.GetBeginAtomIdx()]*deltas[bond.GetEndAtomIdx()] if v != 0.0: res += numpy.sqrt(1./v) return res def _pyChiNv_(mol,order=2): """ From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991) **NOTE**: because the current path finding code does, by design, detect rings as paths (e.g. in C1CC1 there is *1* atom path of length 3), values of ChiNv with N >= 3 may give results that differ from those provided by the old code in molecules that have rings of size 3. """ deltas = numpy.array([(1. / numpy.sqrt(hkd) if hkd!=0.0 else 0.0) for hkd in _hkDeltas(mol, skipHs=0)]) accum = 0.0 for path in Chem.FindAllPathsOfLengthN(mol, order + 1, useBonds=0): accum += numpy.prod(deltas[numpy.array(path)]) return accum def _pyChi2v(mol): """ From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ return _pyChiNv_(mol,2) def _pyChi3v(mol): """ From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ return _pyChiNv_(mol,3) def _pyChi4v(mol): """ From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991) **NOTE**: because the current path finding code does, by design, detect rings as paths (e.g. in C1CC1 there is *1* atom path of length 3), values of Chi4v may give results that differ from those provided by the old code in molecules that have 3 rings. """ return _pyChiNv_(mol,4) def _pyChi0n(mol): """ Similar to Hall Kier Chi0v, but uses nVal instead of valence This makes a big difference after we get out of the first row. """ deltas = [_nVal(x) for x in mol.GetAtoms()] while deltas.count(0): deltas.remove(0) deltas = numpy.array(deltas,'d') res = sum(numpy.sqrt(1./deltas)) return res def _pyChi1n(mol): """ Similar to Hall Kier Chi1v, but uses nVal instead of valence """ delts = numpy.array([_nVal(x) for x in mol.GetAtoms()],'d') res = 0.0 for bond in mol.GetBonds(): v = delts[bond.GetBeginAtomIdx()]*delts[bond.GetEndAtomIdx()] if v != 0.0: res += numpy.sqrt(1./v) return res def _pyChiNn_(mol,order=2): """ Similar to Hall Kier ChiNv, but uses nVal instead of valence This makes a big difference after we get out of the first row. **NOTE**: because the current path finding code does, by design, detect rings as paths (e.g. in C1CC1 there is *1* atom path of length 3), values of ChiNn with N >= 3 may give results that differ from those provided by the old code in molecules that have rings of size 3. """ nval = [_nVal(x) for x in mol.GetAtoms()] deltas = numpy.array([(1. / numpy.sqrt(x) if x else 0.0) for x in nval]) accum = 0.0 for path in Chem.FindAllPathsOfLengthN(mol,order+1,useBonds=0): accum += numpy.prod(deltas[numpy.array(path)]) return accum def _pyChi2n(mol): """ Similar to Hall Kier Chi2v, but uses nVal instead of valence This makes a big difference after we get out of the first row. """ return _pyChiNn_(mol,2) def _pyChi3n(mol): """ Similar to Hall Kier Chi3v, but uses nVal instead of valence This makes a big difference after we get out of the first row. """ return _pyChiNn_(mol,3) def _pyChi4n(mol): """ Similar to Hall Kier Chi4v, but uses nVal instead of valence This makes a big difference after we get out of the first row. **NOTE**: because the current path finding code does, by design, detect rings as paths (e.g. in C1CC1 there is *1* atom path of length 3), values of Chi4n may give results that differ from those provided by the old code in molecules that have 3 rings. """ return _pyChiNn_(mol,4) Chi0v = lambda x:rdMolDescriptors.CalcChi0v(x) Chi0v.version=rdMolDescriptors._CalcChi0v_version Chi1v = lambda x:rdMolDescriptors.CalcChi1v(x) Chi1v.version=rdMolDescriptors._CalcChi1v_version Chi2v = lambda x:rdMolDescriptors.CalcChi2v(x) Chi2v.version=rdMolDescriptors._CalcChi2v_version Chi3v = lambda x:rdMolDescriptors.CalcChi3v(x) Chi3v.version=rdMolDescriptors._CalcChi3v_version Chi4v = lambda x:rdMolDescriptors.CalcChi4v(x) Chi4v.version=rdMolDescriptors._CalcChi4v_version ChiNv_ = lambda x,y:rdMolDescriptors.CalcChiNv(x,y) ChiNv_.version=rdMolDescriptors._CalcChiNv_version Chi0n = lambda x:rdMolDescriptors.CalcChi0n(x) Chi0n.version=rdMolDescriptors._CalcChi0n_version Chi1n = lambda x:rdMolDescriptors.CalcChi1n(x) Chi1n.version=rdMolDescriptors._CalcChi1n_version Chi2n = lambda x:rdMolDescriptors.CalcChi2n(x) Chi2n.version=rdMolDescriptors._CalcChi2n_version Chi3n = lambda x:rdMolDescriptors.CalcChi3n(x) Chi3n.version=rdMolDescriptors._CalcChi3n_version Chi4n = lambda x:rdMolDescriptors.CalcChi4n(x) Chi4n.version=rdMolDescriptors._CalcChi4n_version ChiNn_ = lambda x,y:rdMolDescriptors.CalcChiNn(x,y) ChiNn_.version=rdMolDescriptors._CalcChiNn_version def BalabanJ(mol,dMat=None,forceDMat=0): """ Calculate Balaban's J value for a molecule **Arguments** - mol: a molecule - dMat: (optional) a distance/adjacency matrix for the molecule, if this is not provide, one will be calculated - forceDMat: (optional) if this is set, the distance/adjacency matrix will be recalculated regardless of whether or not _dMat_ is provided or the molecule already has one **Returns** - a float containing the J value We follow the notation of Balaban's paper: Chem. Phys. Lett. vol 89, 399-404, (1982) """ # if no dMat is passed in, calculate one ourselves if forceDMat or dMat is None: if forceDMat: # FIX: should we be using atom weights here or not? dMat = Chem.GetDistanceMatrix(mol,useBO=1,useAtomWts=0,force=1) mol._balabanMat = dMat adjMat = Chem.GetAdjacencyMatrix(mol,useBO=0,emptyVal=0,force=0,prefix="NoBO") mol._adjMat = adjMat else: try: # first check if the molecule already has one dMat = mol._balabanMat except AttributeError: # nope, gotta calculate one dMat = Chem.GetDistanceMatrix(mol,useBO=1,useAtomWts=0,force=0,prefix="Balaban") # now store it mol._balabanMat = dMat try: adjMat = mol._adjMat except AttributeError: adjMat = Chem.GetAdjacencyMatrix(mol,useBO=0,emptyVal=0,force=0,prefix="NoBO") mol._adjMat = adjMat else: adjMat = Chem.GetAdjacencyMatrix(mol,useBO=0,emptyVal=0,force=0,prefix="NoBO") s = _VertexDegrees(dMat) q = _NumAdjacencies(mol,dMat) n = mol.GetNumAtoms() mu = q - n + 1 sum = 0. nS = len(s) for i in range(nS): si = s[i] for j in range(i,nS): if adjMat[i,j] == 1: sum += 1./numpy.sqrt(si*s[j]) if mu+1 != 0: J = float(q) / float(mu + 1) * sum else: J = 0 return J BalabanJ.version="1.0.0" #------------------------------------------------------------------------ # # Start block of BertzCT stuff. # def _AssignSymmetryClasses(mol, vdList, bdMat, forceBDMat, numAtoms, cutoff): """ Used by BertzCT vdList: the number of neighbors each atom has bdMat: "balaban" distance matrix """ if forceBDMat: bdMat = Chem.GetDistanceMatrix(mol,useBO=1,useAtomWts=0,force=1, prefix="Balaban") mol._balabanMat = bdMat atomIdx = 0 keysSeen = [] symList = [0]*numAtoms for i in range(numAtoms): tmpList = bdMat[i].tolist() tmpList.sort() theKey = tuple(['%.4f'%x for x in tmpList[:cutoff]]) try: idx = keysSeen.index(theKey) except ValueError: idx = len(keysSeen) keysSeen.append(theKey) symList[i] = idx+1 return tuple(symList) def _LookUpBondOrder(atom1Id, atom2Id, bondDic): """ Used by BertzCT """ if atom1Id < atom2Id: theKey = (atom1Id,atom2Id) else: theKey = (atom2Id,atom1Id) tmp = bondDic[theKey] if tmp == Chem.BondType.AROMATIC: tmp = 1.5 else: tmp = float(tmp) #tmp = int(tmp) return tmp def _CalculateEntropies(connectionDict, atomTypeDict, numAtoms): """ Used by BertzCT """ connectionList = connectionDict.values() totConnections = sum(connectionList) connectionIE = totConnections*(entropy.InfoEntropy(numpy.array(connectionList)) + math.log(totConnections)/_log2val) atomTypeList = atomTypeDict.values() atomTypeIE = numAtoms*entropy.InfoEntropy(numpy.array(atomTypeList)) return atomTypeIE + connectionIE def _CreateBondDictEtc(mol, numAtoms): """ _Internal Use Only_ Used by BertzCT """ bondDict = {} nList = [None]*numAtoms vdList = [0]*numAtoms for aBond in mol.GetBonds(): atom1=aBond.GetBeginAtomIdx() atom2=aBond.GetEndAtomIdx() if atom1>atom2: atom2,atom1=atom1,atom2 if not aBond.GetIsAromatic(): bondDict[(atom1,atom2)] = aBond.GetBondType() else: # mark Kekulized systems as aromatic bondDict[(atom1,atom2)] = Chem.BondType.AROMATIC if nList[atom1] is None: nList[atom1] = [atom2] elif atom2 not in nList[atom1]: nList[atom1].append(atom2) if nList[atom2] is None: nList[atom2] = [atom1] elif atom1 not in nList[atom2]: nList[atom2].append(atom1) for i,element in enumerate(nList): try: element.sort() vdList[i] = len(element) except: vdList[i] = 0 return bondDict, nList, vdList def BertzCT(mol, cutoff = 100, dMat = None, forceDMat = 1): """ A topological index meant to quantify "complexity" of molecules. Consists of a sum of two terms, one representing the complexity of the bonding, the other representing the complexity of the distribution of heteroatoms. From S. H. Bertz, J. Am. Chem. Soc., vol 103, 3599-3601 (1981) "cutoff" is an integer value used to limit the computational expense. A cutoff value tells the program to consider vertices topologically identical if their distance vectors (sets of distances to all other vertices) are equal out to the "cutoff"th nearest-neighbor. **NOTE** The original implementation had the following comment: > this implementation treats aromatic rings as the > corresponding Kekule structure with alternating bonds, > for purposes of counting "connections". Upon further thought, this is the WRONG thing to do. It results in the possibility of a molecule giving two different CT values depending on the kekulization. For example, in the old implementation, these two SMILES: CC2=CN=C1C3=C(C(C)=C(C=N3)C)C=CC1=C2C CC3=CN=C2C1=NC=C(C)C(C)=C1C=CC2=C3C which correspond to differentk kekule forms, yield different values. The new implementation uses consistent (aromatic) bond orders for aromatic bonds. THIS MEANS THAT THIS IMPLEMENTATION IS NOT BACKWARDS COMPATIBLE. Any molecule containing aromatic rings will yield different values with this implementation. The new behavior is the correct one, so we're going to live with the breakage. **NOTE** this barfs if the molecule contains a second (or nth) fragment that is one atom. """ atomTypeDict = {} connectionDict = {} numAtoms = mol.GetNumAtoms() if forceDMat or dMat is None: if forceDMat: # nope, gotta calculate one dMat = Chem.GetDistanceMatrix(mol,useBO=0,useAtomWts=0,force=1) mol._adjMat = dMat else: try: dMat = mol._adjMat except AttributeError: dMat = Chem.GetDistanceMatrix(mol,useBO=0,useAtomWts=0,force=1) mol._adjMat = dMat if numAtoms < 2: return 0 bondDict, neighborList, vdList = _CreateBondDictEtc(mol, numAtoms) symmetryClasses = _AssignSymmetryClasses(mol, vdList, dMat, forceDMat, numAtoms, cutoff) #print 'Symmm Classes:',symmetryClasses for atomIdx in range(numAtoms): hingeAtomNumber = mol.GetAtomWithIdx(atomIdx).GetAtomicNum() atomTypeDict[hingeAtomNumber] = atomTypeDict.get(hingeAtomNumber,0)+1 hingeAtomClass = symmetryClasses[atomIdx] numNeighbors = vdList[atomIdx] for i in range(numNeighbors): neighbor_iIdx = neighborList[atomIdx][i] NiClass = symmetryClasses[neighbor_iIdx] bond_i_order = _LookUpBondOrder(atomIdx, neighbor_iIdx, bondDict) #print '\t',atomIdx,i,hingeAtomClass,NiClass,bond_i_order if (bond_i_order > 1) and (neighbor_iIdx > atomIdx): numConnections = bond_i_order*(bond_i_order - 1)/2 connectionKey = (min(hingeAtomClass, NiClass), max(hingeAtomClass, NiClass)) connectionDict[connectionKey] = connectionDict.get(connectionKey,0)+numConnections for j in range(i+1, numNeighbors): neighbor_jIdx = neighborList[atomIdx][j] NjClass = symmetryClasses[neighbor_jIdx] bond_j_order = _LookUpBondOrder(atomIdx, neighbor_jIdx, bondDict) numConnections = bond_i_order*bond_j_order connectionKey = (min(NiClass, NjClass), hingeAtomClass, max(NiClass, NjClass)) connectionDict[connectionKey] = connectionDict.get(connectionKey,0)+numConnections if not connectionDict: connectionDict = {'a':1} ks = connectionDict.keys() ks.sort() return _CalculateEntropies(connectionDict, atomTypeDict, numAtoms) BertzCT.version="2.0.0" # Recent Revisions: # 1.0.0 -> 2.0.0: # - force distance matrix updates properly (Fixed as part of Issue 125) # - handle single-atom fragments (Issue 136) # # End block of BertzCT stuff. # #------------------------------------------------------------------------
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/GraphDescriptors.py", "copies": "2", "size": "19929", "license": "bsd-3-clause", "hash": -1105920752131393900, "line_mean": 28.9684210526, "line_max": 105, "alpha_frac": 0.6631541974, "autogenerated": false, "ratio": 2.975810064207854, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9459158542924133, "avg_score": 0.035961143736744035, "num_lines": 665 }
""" class definitions for similarity screening See _SimilarityScreener_ for overview of required API """ from rdkit import DataStructs from rdkit.DataStructs import TopNContainer from rdkit import RDConfig from rdkit import six class SimilarityScreener(object): """ base class important attributes: probe: the probe fingerprint against which we screen. metric: a function that takes two arguments and returns a similarity measure between them dataSource: the source pool from which to draw, needs to support a next() method fingerprinter: a function that takes a molecule and returns a fingerprint of the appropriate format **Notes** subclasses must support either an iterator interface or __len__ and __getitem__ """ def __init__(self,probe=None,metric=None,dataSource=None,fingerprinter=None): self.metric = metric self.dataSource = dataSource self.fingerprinter = fingerprinter self.probe = probe def Reset(self): """ used to reset screeners that behave as iterators """ pass # FIX: add setters/getters for attributes def SetProbe(self,probeFingerprint): """ sets our probe fingerprint """ self.probe = probeFingerprint def GetSingleFingerprint(self,probe): """ returns a fingerprint for a single probe object This is potentially useful in initializing our internal probe object. """ return self.fingerprinter(probe) class ThresholdScreener(SimilarityScreener): """ Used to return all compounds that have a similarity to the probe beyond a threshold value **Notes**: - This is as lazy as possible, so the data source isn't queried until the client asks for a hit. - In addition to being lazy, this class is as thin as possible. (Who'd have thought it was possible!) Hits are *not* stored locally, so if a client resets the iteration and starts over, the same amount of work must be done to retrieve the hits. - The thinness and laziness forces us to support only forward iteration (not random access) """ def __init__(self,threshold,**kwargs): SimilarityScreener.__init__(self,**kwargs) self.threshold = threshold self.dataIter = iter(self.dataSource) # FIX: add setters/getters for attributes def _nextMatch(self): """ *Internal use only* """ done = 0 res = None sim = 0 while not done: # this is going to crap out when the data source iterator finishes, # that's how we stop when no match is found obj = six.next(self.dataIter) fp = self.fingerprinter(obj) sim = DataStructs.FingerprintSimilarity(fp,self.probe,self.metric) if sim >= self.threshold: res = obj done = 1 return sim,res def Reset(self): """ used to reset our internal state so that iteration starts again from the beginning """ self.dataSource.reset() self.dataIter = iter(self.dataSource) def __iter__(self): """ returns an iterator for this screener """ self.Reset() return self def next(self): """ required part of iterator interface """ return self._nextMatch() __next__ = next class TopNScreener(SimilarityScreener): """ A screener that only returns the top N hits found **Notes** - supports forward iteration and getitem """ def __init__(self,num,**kwargs): SimilarityScreener.__init__(self,**kwargs) self.numToGet = num self.topN = None self._pos = 0 def Reset(self): self._pos = 0 def __iter__(self): if self.topN is None: self._initTopN() self.Reset() return self def next(self): if self._pos >= self.numToGet: raise StopIteration else: res = self.topN[self._pos] self._pos += 1 return res __next__ = next def _initTopN(self): self.topN = TopNContainer.TopNContainer(self.numToGet) for obj in self.dataSource: fp = self.fingerprinter(obj) sim = DataStructs.FingerprintSimilarity(fp,self.probe,self.metric) self.topN.Insert(sim,obj) def __len__(self): if self.topN is None: self._initTopN() return self.numToGet def __getitem__(self,idx): if self.topN is None: self._initTopN() return self.topN[idx]
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/Fingerprints/SimilarityScreener.py", "copies": "4", "size": "4666", "license": "bsd-3-clause", "hash": 909492953805852200, "line_mean": 25.5113636364, "line_max": 79, "alpha_frac": 0.6594513502, "autogenerated": false, "ratio": 3.9276094276094278, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0196722677656647, "num_lines": 176 }
""" class definitions for similarity screening See _SimilarityScreener_ for overview of required API """ from rdkit import DataStructs from rdkit import six from rdkit.DataStructs import TopNContainer class SimilarityScreener(object): """ base class important attributes: probe: the probe fingerprint against which we screen. metric: a function that takes two arguments and returns a similarity measure between them dataSource: the source pool from which to draw, needs to support a next() method fingerprinter: a function that takes a molecule and returns a fingerprint of the appropriate format **Notes** subclasses must support either an iterator interface or __len__ and __getitem__ """ def __init__(self, probe=None, metric=None, dataSource=None, fingerprinter=None): self.metric = metric self.dataSource = dataSource self.fingerprinter = fingerprinter self.probe = probe def Reset(self): """ used to reset screeners that behave as iterators """ pass # FIX: add setters/getters for attributes def SetProbe(self, probeFingerprint): """ sets our probe fingerprint """ self.probe = probeFingerprint def GetSingleFingerprint(self, probe): """ returns a fingerprint for a single probe object This is potentially useful in initializing our internal probe object. """ return self.fingerprinter(probe) class ThresholdScreener(SimilarityScreener): """ Used to return all compounds that have a similarity to the probe beyond a threshold value **Notes**: - This is as lazy as possible, so the data source isn't queried until the client asks for a hit. - In addition to being lazy, this class is as thin as possible. (Who'd have thought it was possible!) Hits are *not* stored locally, so if a client resets the iteration and starts over, the same amount of work must be done to retrieve the hits. - The thinness and laziness forces us to support only forward iteration (not random access) """ def __init__(self, threshold, **kwargs): SimilarityScreener.__init__(self, **kwargs) self.threshold = threshold self.dataIter = iter(self.dataSource) # FIX: add setters/getters for attributes def _nextMatch(self): """ *Internal use only* """ done = 0 res = None sim = 0 while not done: # this is going to crap out when the data source iterator finishes, # that's how we stop when no match is found obj = six.next(self.dataIter) fp = self.fingerprinter(obj) sim = DataStructs.FingerprintSimilarity(fp, self.probe, self.metric) if sim >= self.threshold: res = obj done = 1 return sim, res def Reset(self): """ used to reset our internal state so that iteration starts again from the beginning """ self.dataSource.reset() self.dataIter = iter(self.dataSource) def __iter__(self): """ returns an iterator for this screener """ self.Reset() return self def next(self): """ required part of iterator interface """ return self._nextMatch() __next__ = next class TopNScreener(SimilarityScreener): """ A screener that only returns the top N hits found **Notes** - supports forward iteration and getitem """ def __init__(self, num, **kwargs): SimilarityScreener.__init__(self, **kwargs) self.numToGet = num self.topN = None self._pos = 0 def Reset(self): self._pos = 0 def __iter__(self): if self.topN is None: self._initTopN() self.Reset() return self def next(self): if self._pos >= self.numToGet: raise StopIteration else: res = self.topN[self._pos] self._pos += 1 return res __next__ = next def _initTopN(self): self.topN = TopNContainer.TopNContainer(self.numToGet) for obj in self.dataSource: fp = self.fingerprinter(obj) sim = DataStructs.FingerprintSimilarity(fp, self.probe, self.metric) self.topN.Insert(sim, obj) def __len__(self): if self.topN is None: self._initTopN() return self.numToGet def __getitem__(self, idx): if self.topN is None: self._initTopN() return self.topN[idx]
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/Fingerprints/SimilarityScreener.py", "copies": "4", "size": "4634", "license": "bsd-3-clause", "hash": 5622337894783102000, "line_mean": 25.0337078652, "line_max": 83, "alpha_frac": 0.6590418645, "autogenerated": false, "ratio": 3.9271186440677965, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6586160508567797, "avg_score": null, "num_lines": null }
""" #DOC """ class BitEnsemble(object): """ used to store a collection of bits and score BitVects (or signatures) against them. """ def __init__(self, bits=None): if bits is not None: self._bits = list(bits) else: self._bits = [] def SetBits(self, bits): self._bits = list(bits) def AddBit(self, bit): self._bits.append(bit) def GetBits(self): return tuple(self._bits) def GetNumBits(self): return len(self._bits) def ScoreWithOnBits(self, other): """ other must support GetOnBits() """ obl = other.GetOnBits() cnt = 0 for bit in self.GetBits(): if bit in obl: cnt += 1 return cnt def ScoreWithIndex(self, other): """ other must support __getitem__() """ cnt = 0 for bit in self.GetBits(): if other[bit]: cnt += 1 return cnt if __name__ == '__main__': pass
{ "repo_name": "jandom/rdkit", "path": "rdkit/DataStructs/BitEnsemble.py", "copies": "12", "size": "1192", "license": "bsd-3-clause", "hash": 4692827522043586000, "line_mean": 18.5409836066, "line_max": 65, "alpha_frac": 0.6048657718, "autogenerated": false, "ratio": 3.376770538243626, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9981636310043627, "avg_score": null, "num_lines": null }
from __future__ import print_function import sys from rdkit import RDConfig from rdkit.Dbase import DbModule from rdkit import six sqlTextTypes = DbModule.sqlTextTypes sqlIntTypes = DbModule.sqlIntTypes sqlFloatTypes = DbModule.sqlFloatTypes sqlBinTypes = DbModule.sqlBinTypes def GetDbNames(user='sysdba', password='masterkey', dirName='.', dBase='::template1', cn=None): """ returns a list of databases that are available **Arguments** - user: the username for DB access - password: the password to be used for DB access **Returns** - a list of db names (strings) """ if DbModule.getDbSql: if not cn: try: cn = DbModule.connect(dBase, user, password) except Exception: print('Problems opening database: %s' % (dBase)) return [] c = cn.cursor() c.execute(DbModule.getDbSql) if RDConfig.usePgSQL: names = ['::' + str(x[0]) for x in c.fetchall()] else: names = ['::' + str(x[0]) for x in c.fetchall()] names.remove(dBase) elif DbModule.fileWildcard: import os.path import glob names = glob.glob(os.path.join(dirName, DbModule.fileWildcard)) else: names = [] return names def GetTableNames(dBase, user='sysdba', password='masterkey', includeViews=0, cn=None): """ returns a list of tables available in a database **Arguments** - dBase: the name of the DB file to be used - user: the username for DB access - password: the password to be used for DB access - includeViews: if this is non-null, the views in the db will also be returned **Returns** - a list of table names (strings) """ if not cn: try: cn = DbModule.connect(dBase, user, password) except Exception: print('Problems opening database: %s' % (dBase)) return [] c = cn.cursor() if not includeViews: comm = DbModule.getTablesSql else: comm = DbModule.getTablesAndViewsSql c.execute(comm) names = [str(x[0]).upper() for x in c.fetchall()] if RDConfig.usePgSQL and 'PG_LOGDIR_LS' in names: names.remove('PG_LOGDIR_LS') return names def GetColumnInfoFromCursor(cursor): if cursor is None or cursor.description is None: return [] results = [] if not RDConfig.useSqlLite: for item in cursor.description: cName = item[0] cType = item[1] if cType in sqlTextTypes: typeStr = 'string' elif cType in sqlIntTypes: typeStr = 'integer' elif cType in sqlFloatTypes: typeStr = 'float' elif cType in sqlBinTypes: typeStr = 'binary' else: sys.stderr.write('odd type in col %s: %s\n' % (cName, str(cType))) results.append((cName, typeStr)) else: r = cursor.fetchone() if not r: return results for i, v in enumerate(r): cName = cursor.description[i][0] typ = type(v) if isinstance(v, six.string_types): typeStr = 'string' elif typ == int: typeStr = 'integer' elif typ == float: typeStr = 'float' elif (six.PY2 and typ == buffer) or (six.PY3 and typ in (memoryview, bytes)): typeStr = 'binary' else: sys.stderr.write('odd type in col %s: %s\n' % (cName, typ)) results.append((cName, typeStr)) return results def GetColumnNamesAndTypes(dBase, table, user='sysdba', password='masterkey', join='', what='*', cn=None): """ gets a list of columns available in a DB table along with their types **Arguments** - dBase: the name of the DB file to be used - table: the name of the table to query - user: the username for DB access - password: the password to be used for DB access - join: an optional join clause (omit the verb 'join') - what: an optional clause indicating what to select **Returns** - a list of 2-tuples containing: 1) column name 2) column type """ if not cn: cn = DbModule.connect(dBase, user, password) c = cn.cursor() cmd = 'select %s from %s' % (what, table) if join: cmd += ' join %s' % (join) c.execute(cmd) return GetColumnInfoFromCursor(c) def GetColumnNames(dBase, table, user='sysdba', password='masterkey', join='', what='*', cn=None): """ gets a list of columns available in a DB table **Arguments** - dBase: the name of the DB file to be used - table: the name of the table to query - user: the username for DB access - password: the password to be used for DB access - join: an optional join clause (omit the verb 'join') - what: an optional clause indicating what to select **Returns** - a list of column names """ if not cn: cn = DbModule.connect(dBase, user, password) c = cn.cursor() cmd = 'select %s from %s' % (what, table) if join: if join.strip().find('join') != 0: join = 'join %s' % (join) cmd += ' ' + join c.execute(cmd) c.fetchone() desc = c.description res = [str(x[0]) for x in desc] return res
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Dbase/DbInfo.py", "copies": "4", "size": "5375", "license": "bsd-3-clause", "hash": -5955944643313870000, "line_mean": 24.5952380952, "line_max": 98, "alpha_frac": 0.6225116279, "autogenerated": false, "ratio": 3.5245901639344264, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6147101791834426, "avg_score": null, "num_lines": null }
from __future__ import print_function import sys from rdkit import RDConfig from rdkit.Dbase import DbModule sqlTextTypes = DbModule.sqlTextTypes sqlIntTypes = DbModule.sqlIntTypes sqlFloatTypes = DbModule.sqlFloatTypes sqlBinTypes = DbModule.sqlBinTypes def GetDbNames(user='sysdba',password='masterkey',dirName='.',dBase='::template1',cn=None): """ returns a list of databases that are available **Arguments** - user: the username for DB access - password: the password to be used for DB access **Returns** - a list of db names (strings) """ if DbModule.getDbSql: if not cn: try: cn = DbModule.connect(dBase,user,password) except Exception: print('Problems opening database: %s'%(dBase)) return [] c = cn.cursor() c.execute(DbModule.getDbSql) if RDConfig.usePgSQL: names = ['::'+str(x[0]) for x in c.fetchall()] else: names = ['::'+str(x[0]) for x in c.fetchall()] names.remove(dBase) elif DbModule.fileWildcard: import os.path,glob names = glob.glob(os.path.join(dirName,DbModule.fileWildcard)) else: names = [] return names def GetTableNames(dBase,user='sysdba',password='masterkey', includeViews=0,cn=None): """ returns a list of tables available in a database **Arguments** - dBase: the name of the DB file to be used - user: the username for DB access - password: the password to be used for DB access - includeViews: if this is non-null, the views in the db will also be returned **Returns** - a list of table names (strings) """ if not cn: try: cn = DbModule.connect(dBase,user,password) except Exception: print('Problems opening database: %s'%(dBase)) return [] c = cn.cursor() if not includeViews: comm = DbModule.getTablesSql else: comm = DbModule.getTablesAndViewsSql c.execute(comm) names = [str(x[0]).upper() for x in c.fetchall()] if RDConfig.usePgSQL and 'PG_LOGDIR_LS' in names: names.remove('PG_LOGDIR_LS') return names def GetColumnInfoFromCursor(cursor): if cursor is None or cursor.description is None: return [] results = [] if not RDConfig.useSqlLite: for item in cursor.description: cName = item[0] cType = item[1] if cType in sqlTextTypes: typeStr='string' elif cType in sqlIntTypes: typeStr='integer' elif cType in sqlFloatTypes: typeStr='float' elif cType in sqlBinTypes: typeStr='binary' else: sys.stderr.write('odd type in col %s: %s\n'%(cName,str(cType))) results.append((cName,typeStr)) else: from rdkit.six import PY2, PY3 r = cursor.fetchone() if not r: return results for i,v in enumerate(r): cName = cursor.description[i][0] typ = type(v) if typ == str or (PY2 and typ == unicode): typeStr='string' elif typ == int: typeStr='integer' elif typ == float: typeStr='float' elif (PY2 and typ == buffer) or (PY3 and typ in (memoryview, bytes)): typeStr='binary' else: sys.stderr.write('odd type in col %s: %s\n'%(cName,typ)) results.append((cName,typeStr)) return results def GetColumnNamesAndTypes(dBase,table, user='sysdba',password='masterkey', join='',what='*',cn=None): """ gets a list of columns available in a DB table along with their types **Arguments** - dBase: the name of the DB file to be used - table: the name of the table to query - user: the username for DB access - password: the password to be used for DB access - join: an optional join clause (omit the verb 'join') - what: an optional clause indicating what to select **Returns** - a list of 2-tuples containing: 1) column name 2) column type """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() cmd = 'select %s from %s'%(what,table) if join: cmd += ' join %s'%(join) c.execute(cmd) return GetColumnInfoFromCursor(c) def GetColumnNames(dBase,table,user='sysdba',password='masterkey', join='',what='*',cn=None): """ gets a list of columns available in a DB table **Arguments** - dBase: the name of the DB file to be used - table: the name of the table to query - user: the username for DB access - password: the password to be used for DB access - join: an optional join clause (omit the verb 'join') - what: an optional clause indicating what to select **Returns** - a list of column names """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() cmd = 'select %s from %s'%(what,table) if join: if join.strip().find('join') != 0: join = 'join %s'%(join) cmd +=' ' + join c.execute(cmd) c.fetchone() desc = c.description res = [str(x[0]) for x in desc] return res
{ "repo_name": "adalke/rdkit", "path": "rdkit/Dbase/DbInfo.py", "copies": "1", "size": "5367", "license": "bsd-3-clause", "hash": -1086339428606968800, "line_mean": 24.8028846154, "line_max": 91, "alpha_frac": 0.6221352711, "autogenerated": false, "ratio": 3.5637450199203187, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46858802910203184, "avg_score": null, "num_lines": null }
from __future__ import print_function raise NotImplementedError('not finished yet') """ lazy generator of 2D pharmacophore signature data """ import rdkit.Chem from rdkit.Chem.Pharm2D import SigFactory, Matcher, Utils class Generator(object): """ Important attributes: - mol: the molecules whose signature is being worked with - sigFactory : the SigFactory object with signature parameters NOTE: no preprocessing is carried out for _sigFactory_. It *must* be pre-initialized. **Notes** - """ def __init__(self, sigFactory, mol, dMat=None, bitCache=True): """ constructor **Arguments** - sigFactory: a signature factory, see class docs - mol: a molecule, see class docs - dMat: (optional) a distance matrix for the molecule. If this is not provided, one will be calculated - bitCache: (optional) if nonzero, a local cache of which bits have been queried will be maintained. Otherwise things must be recalculate each time a bit is queried. """ if not isinstance(sigFactory, SigFactory.SigFactory): raise ValueError('bad factory') self.sigFactory = sigFactory self.mol = mol if dMat is None: useBO = sigFactory.includeBondOrder dMat = Chem.GetDistanceMatrix(mol, useBO) self.dMat = dMat if bitCache: self.bits = {} else: self.bits = None featFamilies = [fam for fam in sigFactory.featFactory.GetFeatureFamilies() if fam not in sigFactory.skipFeats] nFeats = len(featFamilies) featMatches = {} for fam in featFamilies: featMatches[fam] = [] feats = sigFactory.featFactory.GetFeaturesForMol(mol) for feat in feats: if feat.GetFamily() not in sigFactory.skipFeats: featMatches[feat.GetFamily()].append(feat.GetAtomIds()) featMatches = [None] * nFeats for i in range(nFeats): featMatches[i] = sigFactory.featFactory.GetMolFeature() self.pattMatches = pattMatches def GetBit(self, idx): """ returns a bool indicating whether or not the bit is set """ if idx < 0 or idx >= self.sig.GetSize(): raise IndexError('Index %d invalid' % (idx)) if self.bits is not None and self.bits.has_key(idx): return self.bits[idx] tmp = Matcher.GetAtomsMatchingBit(self.sig, idx, self.mol, dMat=self.dMat, justOne=1, matchingAtoms=self.pattMatches) if not tmp or len(tmp) == 0: res = 0 else: res = 1 if self.bits is not None: self.bits[idx] = res return res def __len__(self): """ allows class to support len() """ return self.sig.GetSize() def __getitem__(self, itm): """ allows class to support random access. Calls self.GetBit() """ return self.GetBit(itm) if __name__ == '__main__': import time from rdkit import RDConfig, Chem from rdkit.Chem.Pharm2D import Gobbi_Pharm2D, Generate import random factory = Gobbi_Pharm2D.factory nToDo = 100 inD = open(RDConfig.RDDataDir + "/NCI/first_5K.smi", 'r').readlines()[:nToDo] mols = [None] * len(inD) for i in range(len(inD)): smi = inD[i].split('\t')[0] smi.strip() mols[i] = Chem.MolFromSmiles(smi) sig = factory.GetSignature() nBits = 300 random.seed(23) bits = [random.randint(0, sig.GetSize() - 1) for x in range(nBits)] print('Using the Lazy Generator') t1 = time.time() for i in range(len(mols)): if not i % 10: print('done mol %d of %d' % (i, len(mols))) gen = Generator(factory, mols[i]) for bit in bits: v = gen[bit] t2 = time.time() print('\tthat took %4.2f seconds' % (t2 - t1)) print('Generating and checking signatures') t1 = time.time() for i in range(len(mols)): if not i % 10: print('done mol %d of %d' % (i, len(mols))) sig = Generate.Gen2DFingerprint(mols[i], factory) for bit in bits: v = sig[bit] t2 = time.time() print('\tthat took %4.2f seconds' % (t2 - t1))
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Pharm2D/LazyGenerator.py", "copies": "1", "size": "4360", "license": "bsd-3-clause", "hash": -3783318194017083400, "line_mean": 26.0807453416, "line_max": 89, "alpha_frac": 0.6311926606, "autogenerated": false, "ratio": 3.3929961089494163, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9453489019131944, "avg_score": 0.014139950083494593, "num_lines": 161 }
from rdkit import RDConfig import DbModule import sys sqlTextTypes = DbModule.sqlTextTypes sqlIntTypes = DbModule.sqlIntTypes sqlFloatTypes = DbModule.sqlFloatTypes sqlBinTypes = DbModule.sqlBinTypes def GetDbNames(user='sysdba',password='masterkey',dirName='.',dBase='::template1',cn=None): """ returns a list of databases that are available **Arguments** - user: the username for DB access - password: the password to be used for DB access **Returns** - a list of db names (strings) """ if DbModule.getDbSql: if not cn: try: cn = DbModule.connect(dBase,user,password) except: print 'Problems opening database: %s'%(dBase) return [] c = cn.cursor() c.execute(DbModule.getDbSql) if RDConfig.usePgSQL: names = ['::'+str(x[0]) for x in c.fetchall()] else: names = ['::'+str(x[0]) for x in c.fetchall()] names.remove(dBase) elif DbModule.fileWildcard: import os.path,glob names = glob.glob(os.path.join(dirName,DbModule.fileWildcard)) else: names = [] return names def GetTableNames(dBase,user='sysdba',password='masterkey', includeViews=0,cn=None): """ returns a list of tables available in a database **Arguments** - dBase: the name of the DB file to be used - user: the username for DB access - password: the password to be used for DB access - includeViews: if this is non-null, the views in the db will also be returned **Returns** - a list of table names (strings) """ if not cn: try: cn = DbModule.connect(dBase,user,password) except: print 'Problems opening database: %s'%(dBase) return [] c = cn.cursor() if not includeViews: comm = DbModule.getTablesSql else: comm = DbModule.getTablesAndViewsSql c.execute(comm) names = [str(x[0]).upper() for x in c.fetchall()] if RDConfig.usePgSQL and 'PG_LOGDIR_LS' in names: names.remove('PG_LOGDIR_LS') return names def GetColumnInfoFromCursor(cursor): if cursor is None or cursor.description is None: return [] results = [] if not RDConfig.useSqlLite: for item in cursor.description: cName = item[0] cType = item[1] if cType in sqlTextTypes: typeStr='string' elif cType in sqlIntTypes: typeStr='integer' elif cType in sqlFloatTypes: typeStr='float' elif cType in sqlBinTypes: typeStr='binary' else: sys.stderr.write('odd type in col %s: %s\n'%(cName,str(cType))) results.append((cName,typeStr)) else: import types r = cursor.fetchone() if not r: return results for i,v in enumerate(r): cName = cursor.description[i][0] typ = type(v) if typ in types.StringTypes: typeStr='string' elif typ == types.IntType: typeStr='integer' elif typ == types.FloatType: typeStr='float' elif typ == types.BufferType: typeStr='binary' else: sys.stderr.write('odd type in col %s: %s\n'%(cName,typ)) results.append((cName,typeStr)) return results def GetColumnNamesAndTypes(dBase,table, user='sysdba',password='masterkey', join='',what='*',cn=None): """ gets a list of columns available in a DB table along with their types **Arguments** - dBase: the name of the DB file to be used - table: the name of the table to query - user: the username for DB access - password: the password to be used for DB access - join: an optional join clause (omit the verb 'join') - what: an optional clause indicating what to select **Returns** - a list of 2-tuples containing: 1) column name 2) column type """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() cmd = 'select %s from %s'%(what,table) if join: cmd += ' join %s'%(join) c.execute(cmd) return GetColumnInfoFromCursor(c) def GetColumnNames(dBase,table,user='sysdba',password='masterkey', join='',what='*',cn=None): """ gets a list of columns available in a DB table **Arguments** - dBase: the name of the DB file to be used - table: the name of the table to query - user: the username for DB access - password: the password to be used for DB access - join: an optional join clause (omit the verb 'join') - what: an optional clause indicating what to select **Returns** - a list of column names """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() cmd = 'select %s from %s'%(what,table) if join: if join.strip().find('join') != 0: join = 'join %s'%(join) cmd +=' ' + join c.execute(cmd) c.fetchone() desc = c.description res = map(lambda x:str(x[0]),desc) return res
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Dbase/DbInfo.py", "copies": "2", "size": "5239", "license": "bsd-3-clause", "hash": 3682971665919595000, "line_mean": 24.556097561, "line_max": 91, "alpha_frac": 0.6220652796, "autogenerated": false, "ratio": 3.5736698499317874, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5195735129531788, "avg_score": null, "num_lines": null }
""" command line utility for growing composite models **Usage** _GrowComposite [optional args] filename_ **Command Line Arguments** - -n *count*: number of new models to build - -C *pickle file name*: name of file containing composite upon which to build. - --inNote *note*: note to be used in loading composite models from the database for growing - --balTable *table name*: table from which to take the original data set (for balancing) - --balWeight *weight*: (between 0 and 1) weighting factor for the new data (for balancing). OR, *weight* can be a list of weights - --balCnt *count*: number of individual models in the balanced composite (for balancing) - --balH: use only the holdout set from the original data set in the balancing (for balancing) - --balT: use only the training set from the original data set in the balancing (for balancing) - -S: shuffle the original data set (for balancing) - -r: randomize the activities of the original data set (for balancing) - -N *note*: note to be attached to the grown composite when it's saved in the database - --outNote *note*: equivalent to -N - -o *filename*: name of an output file to hold the pickled composite after it has been grown. If multiple balance weights are used, the weights will be added to the filenames. - -L *limit*: provide an (integer) limit on individual model complexity - -d *database name*: instead of reading the data from a QDAT file, pull it from a database. In this case, the _filename_ argument provides the name of the database table containing the data set. - -p *tablename*: store persistence data in the database in table *tablename* - -l: locks the random number generator to give consistent sets of training and hold-out data. This is primarily intended for testing purposes. - -g: be less greedy when training the models. - -G *number*: force trees to be rooted at descriptor *number*. - -D: show a detailed breakdown of the composite model performance across the training and, when appropriate, hold-out sets. - -t *threshold value*: use high-confidence predictions for the final analysis of the hold-out data. - -q *list string*: Add QuantTrees to the composite and use the list specified in *list string* as the number of target quantization bounds for each descriptor. Don't forget to include 0's at the beginning and end of *list string* for the name and value fields. For example, if there are 4 descriptors and you want 2 quant bounds apiece, you would use _-q "[0,2,2,2,2,0]"_. Two special cases: 1) If you would like to ignore a descriptor in the model building, use '-1' for its number of quant bounds. 2) If you have integer valued data that should not be quantized further, enter 0 for that descriptor. - -V: print the version number and exit """ from rdkit import RDConfig import numpy from rdkit.ML.Data import DataUtils,SplitData from rdkit.ML import ScreenComposite,BuildComposite from rdkit.ML.Composite import AdjustComposite from rdkit.Dbase.DbConnection import DbConnect from rdkit.ML import CompositeRun import sys,cPickle,time,types _runDetails = CompositeRun.CompositeRun() __VERSION_STRING="0.5.0" _verbose = 1 def message(msg): """ emits messages to _sys.stdout_ override this in modules which import this one to redirect output **Arguments** - msg: the string to be displayed """ if _verbose: sys.stdout.write('%s\n'%(msg)) def GrowIt(details,composite,progressCallback=None, saveIt=1,setDescNames=0,data=None): """ does the actual work of building a composite model **Arguments** - details: a _CompositeRun.CompositeRun_ object containing details (options, parameters, etc.) about the run - composite: the composite model to grow - progressCallback: (optional) a function which is called with a single argument (the number of models built so far) after each model is built. - saveIt: (optional) if this is nonzero, the resulting model will be pickled and dumped to the filename specified in _details.outName_ - setDescNames: (optional) if nonzero, the composite's _SetInputOrder()_ method will be called using the results of the data set's _GetVarNames()_ method; it is assumed that the details object has a _descNames attribute which is passed to the composites _SetDescriptorNames()_ method. Otherwise (the default), _SetDescriptorNames()_ gets the results of _GetVarNames()_. - data: (optional) the data set to be used. If this is not provided, the data set described in details will be used. **Returns** the enlarged composite model """ details.rundate = time.asctime() if data is None: fName = details.tableName.strip() if details.outName == '': details.outName = fName + '.pkl' if details.dbName == '': data = DataUtils.BuildQuantDataSet(fName) elif details.qBounds != []: details.tableName = fName data = details.GetDataSet() else: data = DataUtils.DBToQuantData(details.dbName,fName,quantName=details.qTableName, user=details.dbUser,password=details.dbPassword) nExamples = data.GetNPts() seed = composite._randomSeed DataUtils.InitRandomNumbers(seed) testExamples = [] if details.shuffleActivities == 1: DataUtils.RandomizeActivities(data,shuffle=1,runDetails=details) elif details.randomActivities == 1: DataUtils.RandomizeActivities(data,shuffle=0,runDetails=details) namedExamples = data.GetNamedData() trainExamples = namedExamples nExamples = len(trainExamples) message('Training with %d examples'%(nExamples)) message('\t%d descriptors'%(len(trainExamples[0])-2)) nVars = data.GetNVars() nPossibleVals = composite.nPossibleVals attrs = range(1,nVars+1) if details.useTrees: from rdkit.ML.DecTree import CrossValidate,PruneTree if details.qBounds != []: from rdkit.ML.DecTree import BuildQuantTree builder = BuildQuantTree.QuantTreeBoot else: from rdkit.ML.DecTree import ID3 builder = ID3.ID3Boot driver = CrossValidate.CrossValidationDriver pruner = PruneTree.PruneTree if setDescNames: composite.SetInputOrder(data.GetVarNames()) composite.Grow(trainExamples,attrs,[0]+nPossibleVals, buildDriver=driver, pruner=pruner, nTries=details.nModels,pruneIt=details.pruneIt, lessGreedy=details.lessGreedy,needsQuantization=0, treeBuilder=builder,nQuantBounds=details.qBounds, startAt=details.startAt, maxDepth=details.limitDepth, progressCallback=progressCallback, silent=not _verbose) else: from rdkit.ML.Neural import CrossValidate driver = CrossValidate.CrossValidationDriver composite.Grow(trainExamples,attrs,[0]+nPossibleVals,nTries=details.nModels, buildDriver=driver,needsQuantization=0) composite.AverageErrors() composite.SortModels() modelList,counts,avgErrs = composite.GetAllData() counts = numpy.array(counts) avgErrs = numpy.array(avgErrs) composite._varNames = data.GetVarNames() for i in xrange(len(modelList)): modelList[i].NameModel(composite._varNames) # do final statistics weightedErrs = counts*avgErrs averageErr = sum(weightedErrs)/sum(counts) devs = (avgErrs - averageErr) devs = devs * counts devs = numpy.sqrt(devs*devs) avgDev = sum(devs)/sum(counts) if _verbose: message('# Overall Average Error: %%% 5.2f, Average Deviation: %%% 6.2f'%(100.*averageErr,100.*avgDev)) if details.bayesModel: composite.Train(trainExamples,verbose=0) badExamples = [] if not details.detailedRes: if _verbose: message('Testing all examples') wrong = BuildComposite.testall(composite,namedExamples,badExamples) if _verbose: message('%d examples (%% %5.2f) were misclassified'%(len(wrong),100.*float(len(wrong))/float(len(namedExamples)))) _runDetails.overall_error = float(len(wrong))/len(namedExamples) if details.detailedRes: if _verbose: message('\nEntire data set:') resTup = ScreenComposite.ShowVoteResults(range(data.GetNPts()),data,composite, nPossibleVals[-1],details.threshold) nGood,nBad,nSkip,avgGood,avgBad,avgSkip,voteTab = resTup nPts = len(namedExamples) nClass = nGood+nBad _runDetails.overall_error = float(nBad) / nClass _runDetails.overall_correct_conf = avgGood _runDetails.overall_incorrect_conf = avgBad _runDetails.overall_result_matrix = repr(voteTab) nRej = nClass-nPts if nRej > 0: _runDetails.overall_fraction_dropped = float(nRej)/nPts return composite def GetComposites(details): res = [] if details.persistTblName and details.inNote: conn = DbConnect(details.dbName,details.persistTblName) mdls = conn.GetData(fields='MODEL',where="where note='%s'"%(details.inNote)) for row in mdls: rawD = row[0] res.append(cPickle.loads(str(rawD))) elif details.composFileName: res.append(cPickle.load(open(details.composFileName,'rb'))) return res def BalanceComposite(details,composite,data1=None,data2=None): """ balances the composite using the parameters provided in details **Arguments** - details a _CompositeRun.RunDetails_ object - composite: the composite model to be balanced - data1: (optional) if provided, this should be the data set used to construct the original models - data2: (optional) if provided, this should be the data set used to construct the new individual models """ if not details.balCnt or details.balCnt > len(composite): return composite message("Balancing Composite") # # start by getting data set 1: which is the data set used to build the # original models # if data1 is None: message("\tReading First Data Set") fName = details.balTable.strip() tmp = details.tableName details.tableName = fName dbName = details.dbName details.dbName = details.balDb data1 = details.GetDataSet() details.tableName = tmp details.dbName = dbName if data1 is None: return composite details.splitFrac = composite._splitFrac details.randomSeed = composite._randomSeed DataUtils.InitRandomNumbers(details.randomSeed) if details.shuffleActivities == 1: DataUtils.RandomizeActivities(data1,shuffle=1,runDetails=details) elif details.randomActivities == 1: DataUtils.RandomizeActivities(data1,shuffle=0,runDetails=details) namedExamples = data1.GetNamedData() if details.balDoHoldout or details.balDoTrain: trainIdx,testIdx = SplitData.SplitIndices(len(namedExamples),details.splitFrac, silent=1) trainExamples = [namedExamples[x] for x in trainIdx] testExamples = [namedExamples[x] for x in testIdx] if details.filterFrac != 0.0: trainIdx,temp = DataUtils.FilterData(trainExamples,details.filterVal, details.filterFrac,-1, indicesOnly=1) tmp = [trainExamples[x] for x in trainIdx] testExamples += [trainExamples[x] for x in temp] trainExamples = tmp if details.balDoHoldout: testExamples,trainExamples = trainExamples,testExamples else: trainExamples = namedExamples dataSet1 = trainExamples cols1 = [x.upper() for x in data1.GetVarNames()] data1 = None # # now grab data set 2: the data used to build the new individual models # if data2 is None: message("\tReading Second Data Set") data2 = details.GetDataSet() if data2 is None: return composite details.splitFrac = composite._splitFrac details.randomSeed = composite._randomSeed DataUtils.InitRandomNumbers(details.randomSeed) if details.shuffleActivities == 1: DataUtils.RandomizeActivities(data2,shuffle=1,runDetails=details) elif details.randomActivities == 1: DataUtils.RandomizeActivities(data2,shuffle=0,runDetails=details) dataSet2 = data2.GetNamedData() cols2 = [x.upper() for x in data2.GetVarNames()] data2 = None # and balance it: res = [] weights = details.balWeight if type(weights) not in (types.TupleType,types.ListType): weights = (weights,) for weight in weights: message("\tBalancing with Weight: %.4f"%(weight)) res.append(AdjustComposite.BalanceComposite(composite,dataSet1,dataSet2, weight, details.balCnt, names1=cols1,names2=cols2)) return res def ShowVersion(includeArgs=0): """ prints the version number """ print 'This is GrowComposite.py version %s'%(__VERSION_STRING) if includeArgs: import sys print 'command line was:' print ' '.join(sys.argv) def Usage(): """ provides a list of arguments for when this is used from the command line """ import sys print __doc__ sys.exit(-1) def SetDefaults(runDetails=None): """ initializes a details object with default values **Arguments** - details: (optional) a _CompositeRun.CompositeRun_ object. If this is not provided, the global _runDetails will be used. **Returns** the initialized _CompositeRun_ object. """ if runDetails is None: runDetails = _runDetails return CompositeRun.SetDefaults(runDetails) def ParseArgs(runDetails): """ parses command line arguments and updates _runDetails_ **Arguments** - runDetails: a _CompositeRun.CompositeRun_ object. """ import getopt args,extra = getopt.getopt(sys.argv[1:],'P:o:n:p:b:sf:F:v:hlgd:rSTt:Q:q:DVG:L:C:N:', ['inNote=','outNote=','balTable=','balWeight=','balCnt=', 'balH','balT','balDb=',]) runDetails.inNote='' runDetails.composFileName='' runDetails.balTable='' runDetails.balWeight=(0.5,) runDetails.balCnt=0 runDetails.balDoHoldout=0 runDetails.balDoTrain=0 runDetails.balDb='' for arg,val in args: if arg == '-n': runDetails.nModels = int(val) elif arg == '-C': runDetails.composFileName=val elif arg=='--balTable': runDetails.balTable=val elif arg=='--balWeight': runDetails.balWeight=eval(val) if type(runDetails.balWeight) not in (types.TupleType,types.ListType): runDetails.balWeight=(runDetails.balWeight,) elif arg=='--balCnt': runDetails.balCnt=int(val) elif arg=='--balH': runDetails.balDoHoldout=1 elif arg=='--balT': runDetails.balDoTrain=1 elif arg=='--balDb': runDetails.balDb=val elif arg == '--inNote': runDetails.inNote=val elif arg == '-N' or arg=='--outNote': runDetails.note=val elif arg == '-o': runDetails.outName = val elif arg == '-p': runDetails.persistTblName=val elif arg == '-r': runDetails.randomActivities = 1 elif arg == '-S': runDetails.shuffleActivities = 1 elif arg == '-h': Usage() elif arg == '-l': runDetails.lockRandom = 1 elif arg == '-g': runDetails.lessGreedy=1 elif arg == '-G': runDetails.startAt = int(val) elif arg == '-d': runDetails.dbName=val elif arg == '-T': runDetails.useTrees = 0 elif arg == '-t': runDetails.threshold=float(val) elif arg == '-D': runDetails.detailedRes = 1 elif arg == '-L': runDetails.limitDepth = int(val) elif arg == '-q': qBounds = eval(val) assert type(qBounds) in (types.TupleType,types.ListType),'bad argument type for -q, specify a list as a string' runDetails.qBoundCount=val runDetails.qBounds = qBounds elif arg == '-Q': qBounds = eval(val) assert type(qBounds) in [type([]),type(())],'bad argument type for -Q, specify a list as a string' runDetails.activityBounds=qBounds runDetails.activityBoundsVals=val elif arg == '-V': ShowVersion() sys.exit(0) else: print >>sys.stderr,'bad argument:',arg Usage() runDetails.tableName=extra[0] if not runDetails.balDb: runDetails.balDb=runDetails.dbName if __name__ == '__main__': if len(sys.argv) < 2: Usage() _runDetails.cmd = ' '.join(sys.argv) SetDefaults(_runDetails) ParseArgs(_runDetails) ShowVersion(includeArgs=1) initModels = GetComposites(_runDetails) nModels = len(initModels) if nModels>1: for i in range(nModels): sys.stderr.write('---------------------------------\n\tDoing %d of %d\n---------------------------------\n'%(i+1,nModels)) composite = GrowIt(_runDetails,initModels[i],setDescNames=1) if _runDetails.balTable and _runDetails.balCnt: composites = BalanceComposite(_runDetails,composite) else: composites=[composite] for mdl in composites: mdl.ClearModelExamples() if _runDetails.outName: nWeights = len(_runDetails.balWeight) if nWeights==1: outName = _runDetails.outName composites[0].Pickle(outName) else: for i in range(nWeights): weight = int(100*_runDetails.balWeight[i]) model = composites[i] outName = '%s.%d.pkl'%(_runDetails.outName.split('.pkl')[0],weight) model.Pickle(outName) if _runDetails.persistTblName and _runDetails.dbName: message('Updating results table %s:%s'%(_runDetails.dbName,_runDetails.persistTblName)) if(len(_runDetails.balWeight))>1: message('WARNING: updating results table with models having different weights') # save the composite for i in range(len(composites)): _runDetails.model = cPickle.dumps(composites[i]) _runDetails.Store(db=_runDetails.dbName,table=_runDetails.persistTblName) elif nModels==1: composite = GrowIt(_runDetails,initModels[0],setDescNames=1) if _runDetails.balTable and _runDetails.balCnt: composites = BalanceComposite(_runDetails,composite) else: composites=[composite] for mdl in composites: mdl.ClearModelExamples() if _runDetails.outName: nWeights = len(_runDetails.balWeight) if nWeights==1: outName = _runDetails.outName composites[0].Pickle(outName) else: for i in range(nWeights): weight = int(100*_runDetails.balWeight[i]) model = composites[i] outName = '%s.%d.pkl'%(_runDetails.outName.split('.pkl')[0],weight) model.Pickle(outName) if _runDetails.persistTblName and _runDetails.dbName: message('Updating results table %s:%s'%(_runDetails.dbName,_runDetails.persistTblName)) if(len(composites))>1: message('WARNING: updating results table with models having different weights') for i in range(len(composites)): _runDetails.model = cPickle.dumps(composites[i]) _runDetails.Store(db=_runDetails.dbName,table=_runDetails.persistTblName) else: message("No models found")
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/ML/GrowComposite.py", "copies": "2", "size": "19705", "license": "bsd-3-clause", "hash": -7406231364026530000, "line_mean": 33.8144876325, "line_max": 128, "alpha_frac": 0.6660746004, "autogenerated": false, "ratio": 3.759778668193093, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5425853268593093, "avg_score": null, "num_lines": null }
""" unit testing code for the Smiles file handling stuff """ import unittest from rdkit import Chem from rdkit.six import next from rdkit import RDLogger class TestCase(unittest.TestCase): def setUp(self): self.smis = ['CC', 'CCC', 'CCCCC', 'CCCCCC', 'CCCCCCC', 'CC', 'CCCCOC'] self.nMolecules = len(self.smis) def tearDown(self): RDLogger.EnableLog('rdApp.error') def assertMolecule(self, mol, i, msg=''): """ Assert that we have a valid molecule """ self.assertIsNotNone(mol, '{0}read {1} failed'.format(msg, i)) self.assertGreater(mol.GetNumAtoms(), 0, '{0}no atoms in mol {1}'.format(msg, i)) def test_SmilesReaderIndex(self): # tests lazy reads supp = Chem.SmilesMolSupplierFromText('\n'.join(self.smis), ',', 0, -1, 0) for i in range(4): self.assertMolecule(next(supp), i) i = len(supp) - 1 self.assertMolecule(supp[i], i) # Use in a list comprehension ms = [Chem.MolToSmiles(mol) for mol in supp] self.assertEqual(ms, self.smis) self.assertEqual(len(supp), self.nMolecules, 'bad supplier length') # Despite iterating through the whole supplier, we can still access by index i = self.nMolecules - 3 self.assertMolecule(supp[i - 1], i, msg='back index: ') with self.assertRaises(IndexError): _ = supp[self.nMolecules] # out of bound read must fail # and we can access with negative numbers mol1 = supp[len(supp) - 1] mol2 = supp[-1] self.assertEqual(Chem.MolToSmiles(mol1), Chem.MolToSmiles(mol2)) def test_SmilesReaderIterator(self): # tests lazy reads using the iterator interface " supp = Chem.SmilesMolSupplierFromText('\n'.join(self.smis), ',', 0, -1, 0) nDone = 0 for mol in supp: self.assertMolecule(mol, nDone) nDone += 1 self.assertEqual(nDone, self.nMolecules, 'bad number of molecules') self.assertEqual(len(supp), self.nMolecules, 'bad supplier length') # Despite iterating through the whole supplier, we can still access by index i = self.nMolecules - 3 self.assertMolecule(supp[i - 1], i, msg='back index: ') with self.assertRaises(IndexError): _ = supp[self.nMolecules] # out of bound read must not fail def test_SmilesReaderBoundaryConditions(self): # Suppress the error message due to the incorrect smiles RDLogger.DisableLog('rdApp.error') smis = ['CC', 'CCOC', 'fail', 'CCO'] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis), ',', 0, -1, 0) self.assertEqual(len(supp), 4) self.assertIsNone(supp[2]) self.assertIsNotNone(supp[3]) supp = Chem.SmilesMolSupplierFromText('\n'.join(smis), ',', 0, -1, 0) self.assertIsNone(supp[2]) self.assertIsNotNone(supp[3]) self.assertEqual(len(supp), 4) with self.assertRaises(IndexError): supp[4] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis), ',', 0, -1, 0) self.assertEqual(len(supp), 4) self.assertIsNotNone(supp[3]) with self.assertRaises(IndexError): supp[4] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis), ',', 0, -1, 0) with self.assertRaises(IndexError): supp[4] self.assertEqual(len(supp), 4) self.assertIsNotNone(supp[3]) if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/Suppliers/UnitTestSmilesMolSupplier.py", "copies": "4", "size": "3573", "license": "bsd-3-clause", "hash": -4142047755766020600, "line_mean": 30.6194690265, "line_max": 85, "alpha_frac": 0.6644276518, "autogenerated": false, "ratio": 3.213129496402878, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5877557148202878, "avg_score": null, "num_lines": null }
raise NotImplementedError,'not finished yet' """ lazy generator of 2D pharmacophore signature data """ import rdkit.Chem from rdkit.Chem.Pharm2D import SigFactory,Matcher,Utils class Generator(object): """ Important attributes: - mol: the molecules whose signature is being worked with - sigFactory : the SigFactory object with signature parameters NOTE: no preprocessing is carried out for _sigFactory_. It *must* be pre-initialized. **Notes** - """ def __init__(self,sigFactory,mol,dMat=None,bitCache=True): """ constructor **Arguments** - sigFactory: a signature factory, see class docs - mol: a molecule, see class docs - dMat: (optional) a distance matrix for the molecule. If this is not provided, one will be calculated - bitCache: (optional) if nonzero, a local cache of which bits have been queried will be maintained. Otherwise things must be recalculate each time a bit is queried. """ if not isinstance(sigFactory,SigFactory.SigFactory): raise ValueError,'bad factory' self.sigFactory = sigFactory self.mol = mol if dMat is None: useBO = sigFactory.includeBondOrder dMat = Chem.GetDistanceMatrix(mol,useBO) self.dMat = dMat if bitCache: self.bits = {} else: self.bits = None featFamilies=[fam for fam in sigFactory.featFactory.GetFeatureFamilies() if fam not in sigFactory.skipFeats] nFeats = len(featFamilies) featMatches={} for fam in featFamilies: featMatches[fam] = [] feats = sigFactory.featFactory.GetFeaturesForMol(mol) for feat in feats: if feat.GetFamily() not in sigFactory.skipFeats: featMatches[feat.GetFamily()].append(feat.GetAtomIds()) featMatches = [None]*nFeats for i in range(nFeats): featMatches[i]=sigFactory.featFactory.GetMolFeature() self.pattMatches = pattMatches def GetBit(self,idx): """ returns a bool indicating whether or not the bit is set """ if idx < 0 or idx >= self.sig.GetSize(): raise IndexError,'Index %d invalid'%(idx) if self.bits is not None and self.bits.has_key(idx): return self.bits[idx] tmp = Matcher.GetAtomsMatchingBit(self.sig,idx,self.mol, dMat=self.dMat,justOne=1, matchingAtoms=self.pattMatches) if not tmp or len(tmp)==0: res = 0 else: res = 1 if self.bits is not None: self.bits[idx] = res return res def __len__(self): """ allows class to support len() """ return self.sig.GetSize() def __getitem__(self,itm): """ allows class to support random access. Calls self.GetBit() """ return self.GetBit(itm) if __name__ == '__main__': import time from rdkit import RDConfig,Chem from rdkit.Chem.Pharm2D import Gobbi_Pharm2D,Generate import random factory = Gobbi_Pharm2D.factory nToDo=100 inD = open(RDConfig.RDDataDir+"/NCI/first_5K.smi",'r').readlines()[:nToDo] mols = [None]*len(inD) for i in range(len(inD)): smi = inD[i].split('\t')[0] smi.strip() mols[i] = Chem.MolFromSmiles(smi) sig = factory.GetSignature() nBits = 300 random.seed(23) bits = [random.randint(0,sig.GetSize()-1) for x in range(nBits)] print 'Using the Lazy Generator' t1 = time.time() for i in range(len(mols)): if not i % 10: print 'done mol %d of %d'%(i,len(mols)) gen = Generator(factory,mols[i]) for bit in bits: v = gen[bit] t2 = time.time() print '\tthat took %4.2f seconds'%(t2-t1) print 'Generating and checking signatures' t1 = time.time() for i in range(len(mols)): if not i % 10: print 'done mol %d of %d'%(i,len(mols)) sig = Generate.Gen2DFingerprint(mols[i],factory) for bit in bits: v = sig[bit] t2 = time.time() print '\tthat took %4.2f seconds'%(t2-t1)
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Pharm2D/LazyGenerator.py", "copies": "2", "size": "4289", "license": "bsd-3-clause", "hash": 6513829194663768000, "line_mean": 26.4935897436, "line_max": 112, "alpha_frac": 0.6348799254, "autogenerated": false, "ratio": 3.4120922832140015, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5046972208614002, "avg_score": null, "num_lines": null }
""" Supplies a class for working with fingerprints from databases #DOC """ from rdkit import RDConfig from rdkit.VLib.Node import VLibNode from rdkit import DataStructs import cPickle import sys def warning(msg,dest=sys.stderr): dest.write(msg) class DbFpSupplier(VLibNode): """ new fps come back with all additional fields from the database set in a "_fieldsFromDb" data member """ def __init__(self,dbResults,fpColName='AutoFragmentFp',usePickles=True): """ DbResults should be a subclass of Dbase.DbResultSet.DbResultBase """ VLibNode.__init__(self) self._usePickles = usePickles self._data = dbResults self._fpColName = fpColName.upper() self._colNames = [x.upper() for x in self._data.GetColumnNames()] if self._fpColName not in self._colNames: raise ValueError,'fp column name "%s" not found in result set: %s'%(self._fpColName,str(self._colNames)) self.fpCol = self._colNames.index(self._fpColName) del self._colNames[self.fpCol] self._colNames = tuple(self._colNames) self._numProcessed=0 def GetColumnNames(self): return self._colNames def _BuildFp(self,data): data = list(data) pkl = str(data[self.fpCol]) del data[self.fpCol] self._numProcessed+=1; try: if self._usePickles: newFp = cPickle.loads(pkl) else: newFp = DataStructs.ExplicitBitVect(pkl) except: import traceback traceback.print_exc() newFp = None if newFp: newFp._fieldsFromDb = data return newFp def next(self): itm = self.NextItem() if itm is None: raise StopIteration return itm class ForwardDbFpSupplier(DbFpSupplier): """ DbFp supplier supporting only forward iteration >>> import os.path >>> from rdkit.Dbase.DbConnection import DbConnect >>> fName = RDConfig.RDTestDatabase >>> conn = DbConnect(fName,'simple_combined') >>> suppl = ForwardDbFpSupplier(conn.GetData()) we can loop over the supplied fingerprints: >>> fps = [] >>> for fp in suppl: ... fps.append(fp) >>> len(fps) 12 """ def __init__(self,*args,**kwargs): DbFpSupplier.__init__(self,*args,**kwargs) self.reset() def reset(self): DbFpSupplier.reset(self) self._dataIter = iter(self._data) def NextItem(self): """ NOTE: this has side effects """ try: d = self._dataIter.next() except StopIteration: d = None if d is not None: newFp = self._BuildFp(d) else: newFp = None return newFp class RandomAccessDbFpSupplier(DbFpSupplier): """ DbFp supplier supporting random access: >>> import os.path >>> from rdkit.Dbase.DbConnection import DbConnect >>> fName = RDConfig.RDTestDatabase >>> conn = DbConnect(fName,'simple_combined') >>> suppl = RandomAccessDbFpSupplier(conn.GetData()) >>> len(suppl) 12 we can pull individual fingerprints: >>> fp = suppl[5] >>> fp.GetNumBits() 128 >>> fp.GetNumOnBits() 54 a standard loop over the fingerprints: >>> fps = [] >>> for fp in suppl: ... fps.append(fp) >>> len(fps) 12 or we can use an indexed loop: >>> fps = [None]*len(suppl) >>> for i in range(len(suppl)): ... fps[i] = suppl[i] >>> len(fps) 12 """ def __init__(self,*args,**kwargs): DbFpSupplier.__init__(self,*args,**kwargs) self.reset() def __len__(self): return len(self._data) def __getitem__(self,idx): newD = self._data[idx] return self._BuildFp(newD) def reset(self): self._pos = -1 def NextItem(self): self._pos += 1 res = None if self._pos < len(self): res = self[self._pos] return res #------------------------------------ # # 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/Fingerprints/DbFpSupplier.py", "copies": "2", "size": "4222", "license": "bsd-3-clause", "hash": 1819110671782756900, "line_mean": 21.9456521739, "line_max": 110, "alpha_frac": 0.6307437234, "autogenerated": false, "ratio": 3.3217938630999213, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4952537586499921, "avg_score": null, "num_lines": null }
""" Supplies a class for working with molecules from databases #DOC """ from rdkit import Chem from rdkit.Chem.Suppliers.MolSupplier import MolSupplier import sys def warning(msg,dest=sys.stderr): dest.write(msg) class DbMolSupplier(MolSupplier): """ new molecules come back with all additional fields from the database set in a "_fieldsFromDb" data member """ def __init__(self,dbResults, molColumnFormats={'SMILES':'SMI', 'SMI':'SMI', 'MOLPKL':'PKL'}, nameCol='', transformFunc=None, **kwargs): """ DbResults should be a subclass of Dbase.DbResultSet.DbResultBase """ self._data = dbResults self._colNames = [x.upper() for x in self._data.GetColumnNames()] nameCol = nameCol.upper() self.molCol = -1 self.transformFunc=transformFunc try: self.nameCol = self._colNames.index(nameCol) except ValueError: self.nameCol = -1 for name in molColumnFormats.keys(): name = name.upper() try: idx = self._colNames.index(name) except ValueError: pass else: self.molCol = idx self.molFmt = molColumnFormats[name] break if self.molCol < 0: raise ValueError('DbResultSet has no recognizable molecule column') del self._colNames[self.molCol] self._colNames = tuple(self._colNames) self._numProcessed=0 def GetColumnNames(self): return self._colNames def _BuildMol(self,data): data = list(data) molD = data[self.molCol] del data[self.molCol] self._numProcessed+=1; try: if self.molFmt =='SMI': newM = Chem.MolFromSmiles(str(molD)) if not newM: warning('Problems processing mol %d, smiles: %s\n'%(self._numProcessed,molD)) elif self.molFmt =='PKL': newM = Chem.Mol(str(molD)) except Exception: import traceback traceback.print_exc() newM = None else: if newM and self.transformFunc: try: newM = self.transformFunc(newM,data) except Exception: import traceback traceback.print_exc() newM = None if newM: newM._fieldsFromDb = data nFields = len(data) for i in range(nFields): newM.SetProp(self._colNames[i],str(data[i])) if self.nameCol >=0 : newM.SetProp('_Name',str(data[self.nameCol])) return newM class ForwardDbMolSupplier(DbMolSupplier): """ DbMol supplier supporting only forward iteration new molecules come back with all additional fields from the database set in a "_fieldsFromDb" data member """ def __init__(self,dbResults,**kwargs): """ DbResults should be an iterator for Dbase.DbResultSet.DbResultBase """ DbMolSupplier.__init__(self,dbResults,**kwargs) self.Reset() def Reset(self): self._dataIter = iter(self._data) def NextMol(self): """ NOTE: this has side effects """ try: d = self._dataIter.next() except StopIteration: d = None if d is not None: newM = self._BuildMol(d) else: newM = None return newM class RandomAccessDbMolSupplier(DbMolSupplier): def __init__(self,dbResults,**kwargs): """ DbResults should be a Dbase.DbResultSet.RandomAccessDbResultSet """ DbMolSupplier.__init__(self,dbResults,**kwargs) self._pos = -1 def __len__(self): return len(self._data) def __getitem__(self,idx): newD = self._data[idx] return self._BuildMol(newD) def Reset(self): self._pos = -1 def NextMol(self): self._pos += 1 res = None if self._pos < len(self): res = self[self._pos] return res
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/Suppliers/DbMolSupplier.py", "copies": "1", "size": "4108", "license": "bsd-3-clause", "hash": 6291392567617086000, "line_mean": 24.675, "line_max": 87, "alpha_frac": 0.6085686465, "autogenerated": false, "ratio": 3.594050743657043, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9546244839223041, "avg_score": 0.031274910186800245, "num_lines": 160 }
""" Supplies a class for working with molecules from databases #DOC """ from rdkit import Chem from rdkit.Chem.Suppliers.MolSupplier import MolSupplier import sys def warning(msg, dest=sys.stderr): dest.write(msg) class DbMolSupplier(MolSupplier): """ new molecules come back with all additional fields from the database set in a "_fieldsFromDb" data member """ def __init__(self, dbResults, molColumnFormats={'SMILES': 'SMI', 'SMI': 'SMI', 'MOLPKL': 'PKL'}, nameCol='', transformFunc=None, **kwargs): """ DbResults should be a subclass of Dbase.DbResultSet.DbResultBase """ self._data = dbResults self._colNames = [x.upper() for x in self._data.GetColumnNames()] nameCol = nameCol.upper() self.molCol = -1 self.transformFunc = transformFunc try: self.nameCol = self._colNames.index(nameCol) except ValueError: self.nameCol = -1 for name in molColumnFormats.keys(): name = name.upper() try: idx = self._colNames.index(name) except ValueError: pass else: self.molCol = idx self.molFmt = molColumnFormats[name] break if self.molCol < 0: raise ValueError('DbResultSet has no recognizable molecule column') del self._colNames[self.molCol] self._colNames = tuple(self._colNames) self._numProcessed = 0 def GetColumnNames(self): return self._colNames def _BuildMol(self, data): data = list(data) molD = data[self.molCol] del data[self.molCol] self._numProcessed += 1 try: if self.molFmt == 'SMI': newM = Chem.MolFromSmiles(str(molD)) if not newM: warning('Problems processing mol %d, smiles: %s\n' % (self._numProcessed, molD)) elif self.molFmt == 'PKL': newM = Chem.Mol(str(molD)) except Exception: import traceback traceback.print_exc() newM = None else: if newM and self.transformFunc: try: newM = self.transformFunc(newM, data) except Exception: import traceback traceback.print_exc() newM = None if newM: newM._fieldsFromDb = data nFields = len(data) for i in range(nFields): newM.SetProp(self._colNames[i], str(data[i])) if self.nameCol >= 0: newM.SetProp('_Name', str(data[self.nameCol])) return newM class ForwardDbMolSupplier(DbMolSupplier): """ DbMol supplier supporting only forward iteration new molecules come back with all additional fields from the database set in a "_fieldsFromDb" data member """ def __init__(self, dbResults, **kwargs): """ DbResults should be an iterator for Dbase.DbResultSet.DbResultBase """ DbMolSupplier.__init__(self, dbResults, **kwargs) self.Reset() def Reset(self): self._dataIter = iter(self._data) def NextMol(self): """ NOTE: this has side effects """ try: d = self._dataIter.next() except StopIteration: d = None if d is not None: newM = self._BuildMol(d) else: newM = None return newM class RandomAccessDbMolSupplier(DbMolSupplier): def __init__(self, dbResults, **kwargs): """ DbResults should be a Dbase.DbResultSet.RandomAccessDbResultSet """ DbMolSupplier.__init__(self, dbResults, **kwargs) self._pos = -1 def __len__(self): return len(self._data) def __getitem__(self, idx): newD = self._data[idx] return self._BuildMol(newD) def Reset(self): self._pos = -1 def NextMol(self): self._pos += 1 res = None if self._pos < len(self): res = self[self._pos] return res
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Suppliers/DbMolSupplier.py", "copies": "1", "size": "4118", "license": "bsd-3-clause", "hash": -184740302200689800, "line_mean": 23.6586826347, "line_max": 99, "alpha_frac": 0.6070908208, "autogenerated": false, "ratio": 3.5902353966870098, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.469732621748701, "avg_score": null, "num_lines": null }
""" This functionality gets mixed into the BitEnsemble class """ from rdkit.DataStructs.BitEnsemble import BitEnsemble def _InitScoreTable(self,dbConn,tableName,idInfo='',actInfo=''): """ inializes a db table to store our scores idInfo and actInfo should be strings with the definitions of the id and activity columns of the table (when desired) """ if idInfo: cols = [idInfo] else: cols = [] for bit in self.GetBits(): cols.append('Bit_%d smallint'%(bit)) if actInfo : cols.append(actInfo) dbConn.AddTable(tableName,','.join(cols)) self._dbTableName=tableName def _ScoreToDb(self,sig,dbConn,tableName=None,id=None,act=None): """ scores the "signature" that is passed in and puts the results in the db table """ if tableName is None: try: tableName = self._dbTableName except AttributeError: raise ValueError,'table name not set in BitEnsemble pre call to ScoreToDb()' if id is not None: cols = [id] else: cols = [] score = 0 for bit in self.GetBits(): b = sig[bit] cols.append(b) score += b if act is not None: cols.append(act) dbConn.InsertData(tableName,cols) BitEnsemble.InitScoreTable = _InitScoreTable BitEnsemble.ScoreToDb = _ScoreToDb
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/DataStructs/BitEnsembleDb.py", "copies": "2", "size": "1558", "license": "bsd-3-clause", "hash": 4183451119366675500, "line_mean": 25.406779661, "line_max": 82, "alpha_frac": 0.6874197689, "autogenerated": false, "ratio": 3.3869565217391306, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5074376290639131, "avg_score": null, "num_lines": null }
""" This functionality gets mixed into the BitEnsemble class """ from rdkit.DataStructs.BitEnsemble import BitEnsemble def _InitScoreTable(self, dbConn, tableName, idInfo='', actInfo=''): """ inializes a db table to store our scores idInfo and actInfo should be strings with the definitions of the id and activity columns of the table (when desired) """ if idInfo: cols = [idInfo] else: cols = [] for bit in self.GetBits(): cols.append('Bit_%d smallint' % (bit)) if actInfo: cols.append(actInfo) dbConn.AddTable(tableName, ','.join(cols)) self._dbTableName = tableName def _ScoreToDb(self, sig, dbConn, tableName=None, id=None, act=None): """ scores the "signature" that is passed in and puts the results in the db table """ if tableName is None: try: tableName = self._dbTableName except AttributeError: raise ValueError('table name not set in BitEnsemble pre call to ScoreToDb()') if id is not None: cols = [id] else: cols = [] score = 0 for bit in self.GetBits(): b = sig[bit] cols.append(b) score += b if act is not None: cols.append(act) dbConn.InsertData(tableName, cols) BitEnsemble.InitScoreTable = _InitScoreTable BitEnsemble.ScoreToDb = _ScoreToDb
{ "repo_name": "rvianello/rdkit", "path": "rdkit/DataStructs/BitEnsembleDb.py", "copies": "11", "size": "1569", "license": "bsd-3-clause", "hash": 8975726138144633000, "line_mean": 24.7213114754, "line_max": 83, "alpha_frac": 0.6826003824, "autogenerated": false, "ratio": 3.4332603938730855, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9615860776273086, "avg_score": null, "num_lines": null }
""" unit testing code for BitEnsembles """ from rdkit import RDConfig import os import unittest from rdkit.DataStructs.BitEnsemble import BitEnsemble from rdkit.DataStructs import BitEnsembleDb from rdkit.DataStructs import SparseBitVect class TestCase(unittest.TestCase): def test1(self): ensemble = BitEnsemble() ensemble.SetBits([1,11,21,31]) bv = SparseBitVect(100) bv.SetBit(1) bv.SetBit(11) bv.SetBit(13) score = ensemble.ScoreWithOnBits(bv) assert score==2,'bad score: %d'%(score) score = ensemble.ScoreWithIndex(bv) assert score==2,'bad score: %d'%(score) def test2(self): ensemble = BitEnsemble([1,11,21,31]) bv = SparseBitVect(100) bv.SetBit(1) bv.SetBit(11) bv.SetBit(13) score = ensemble.ScoreWithOnBits(bv) assert score==2,'bad score: %d'%(score) score = ensemble.ScoreWithIndex(bv) assert score==2,'bad score: %d'%(score) def test3(self): ensemble = BitEnsemble() for bit in [1,11,21,31]: ensemble.AddBit(bit) bv = SparseBitVect(100) bv.SetBit(1) bv.SetBit(11) bv.SetBit(13) score = ensemble.ScoreWithOnBits(bv) assert score==2,'bad score: %d'%(score) score = ensemble.ScoreWithIndex(bv) assert score==2,'bad score: %d'%(score) def _setupDb(self): from rdkit.Dbase.DbConnection import DbConnect fName = RDConfig.RDTestDatabase self.conn = DbConnect(fName) self.dbTblName = 'bit_ensemble_test' return self.conn def testdb1(self): """ test the sig - db functionality """ conn = self._setupDb() ensemble = BitEnsemble() for bit in [1,3,4]: ensemble.AddBit(bit) sigBs = [([0,0,0,0,0,0],(0,0,0)), ([0,1,0,1,0,0],(1,1,0)), ([0,1,0,0,1,0],(1,0,1)), ([0,1,0,0,1,1],(1,0,1)), ] ensemble.InitScoreTable(conn,self.dbTblName) for bs,tgt in sigBs: ensemble.ScoreToDb(bs,conn) conn.Commit() d = conn.GetData(table=self.dbTblName) assert len(d) == len(sigBs),'bad number of results returned' for i in range(len(sigBs)): bs,tgt = tuple(sigBs[i]) dbRes = tuple(d[i]) assert dbRes==tgt,'bad bits returned: %s != %s'%(str(dbRes),str(tgt)) d = None self.conn = None def testdb2(self): """ test the sig - db functionality """ conn = self._setupDb() ensemble = BitEnsemble() for bit in [1,3,4]: ensemble.AddBit(bit) sigBs = [([0,0,0,0,0,0],(0,0,0)), ([0,1,0,1,0,0],(1,1,0)), ([0,1,0,0,1,0],(1,0,1)), ([0,1,0,0,1,1],(1,0,1)), ] ensemble.InitScoreTable(conn,self.dbTblName,idInfo='id varchar(10)',actInfo='act int') for bs,tgt in sigBs: ensemble.ScoreToDb(bs,conn,id='foo',act=1) conn.Commit() d = conn.GetData(table=self.dbTblName) assert len(d) == len(sigBs),'bad number of results returned' for i in range(len(sigBs)): bs,tgt = tuple(sigBs[i]) dbRes = tuple(d[i]) assert dbRes[1:-1]==tgt,'bad bits returned: %s != %s'%(str(dbRes[1:-1]),str(tgt)) d = None self.conn = None if __name__ == '__main__': unittest.main()
{ "repo_name": "strets123/rdkit", "path": "rdkit/DataStructs/UnitTestBitEnsemble.py", "copies": "5", "size": "3478", "license": "bsd-3-clause", "hash": 8430484689723324000, "line_mean": 27.5081967213, "line_max": 90, "alpha_frac": 0.6043703278, "autogenerated": false, "ratio": 2.922689075630252, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6027059403430252, "avg_score": null, "num_lines": null }
""" unit testing code for BitEnsembles """ import os import shutil import tempfile import unittest from rdkit import RDConfig from rdkit.DataStructs import SparseBitVect # This import is important to initialize the BitEnsemble module from rdkit.DataStructs import BitEnsembleDb from rdkit.DataStructs.BitEnsemble import BitEnsemble class TestCase(unittest.TestCase): def test1(self): ensemble = BitEnsemble() ensemble.SetBits([1, 11, 21, 31]) self.assertEqual(ensemble.GetNumBits(), 4) bv = SparseBitVect(100) bv.SetBit(1) bv.SetBit(11) bv.SetBit(13) score = ensemble.ScoreWithOnBits(bv) assert score == 2, 'bad score: %d' % (score) score = ensemble.ScoreWithIndex(bv) assert score == 2, 'bad score: %d' % (score) def test2(self): ensemble = BitEnsemble([1, 11, 21, 31]) bv = SparseBitVect(100) bv.SetBit(1) bv.SetBit(11) bv.SetBit(13) score = ensemble.ScoreWithOnBits(bv) assert score == 2, 'bad score: %d' % (score) score = ensemble.ScoreWithIndex(bv) assert score == 2, 'bad score: %d' % (score) def test3(self): ensemble = BitEnsemble() for bit in [1, 11, 21, 31]: ensemble.AddBit(bit) bv = SparseBitVect(100) bv.SetBit(1) bv.SetBit(11) bv.SetBit(13) score = ensemble.ScoreWithOnBits(bv) assert score == 2, 'bad score: %d' % (score) score = ensemble.ScoreWithIndex(bv) assert score == 2, 'bad score: %d' % (score) def _setupDb(self): from rdkit.Dbase.DbConnection import DbConnect fName = RDConfig.RDTestDatabase if RDConfig.useSqlLite: _, tempName = tempfile.mkstemp(suffix='sqlt') self.tempDbName = tempName shutil.copyfile(fName, tempName) else: # pragma: nocover tempName = '::RDTests' self.conn = DbConnect(tempName) self.dbTblName = 'bit_ensemble_test' return self.conn def tearDown(self): if hasattr(self, 'tempDbName') and RDConfig.useSqlLite and os.path.exists(self.tempDbName): try: os.unlink(self.tempDbName) except: # pragma: nocover import traceback traceback.print_exc() def testdb1(self): """ test the sig - db functionality """ conn = self._setupDb() ensemble = BitEnsemble() for bit in [1, 3, 4]: ensemble.AddBit(bit) sigBs = [([0, 0, 0, 0, 0, 0], (0, 0, 0)), ([0, 1, 0, 1, 0, 0], (1, 1, 0)), ([0, 1, 0, 0, 1, 0], (1, 0, 1)), ([0, 1, 0, 0, 1, 1], (1, 0, 1)), ] ensemble.InitScoreTable(conn, self.dbTblName) for bs, tgt in sigBs: ensemble.ScoreToDb(bs, conn) conn.Commit() d = conn.GetData(table=self.dbTblName) assert len(d) == len(sigBs), 'bad number of results returned' for i in range(len(sigBs)): bs, tgt = tuple(sigBs[i]) dbRes = tuple(d[i]) assert dbRes == tgt, 'bad bits returned: %s != %s' % (str(dbRes), str(tgt)) d = None self.conn = None def testdb2(self): """ test the sig - db functionality """ conn = self._setupDb() ensemble = BitEnsemble() for bit in [1, 3, 4]: ensemble.AddBit(bit) sigBs = [([0, 0, 0, 0, 0, 0], (0, 0, 0)), ([0, 1, 0, 1, 0, 0], (1, 1, 0)), ([0, 1, 0, 0, 1, 0], (1, 0, 1)), ([0, 1, 0, 0, 1, 1], (1, 0, 1)), ] ensemble.InitScoreTable(conn, self.dbTblName, idInfo='id varchar(10)', actInfo='act int') for bs, tgt in sigBs: ensemble.ScoreToDb(bs, conn, id='foo', act=1) conn.Commit() d = conn.GetData(table=self.dbTblName) assert len(d) == len(sigBs), 'bad number of results returned' for i in range(len(sigBs)): bs, tgt = tuple(sigBs[i]) dbRes = tuple(d[i]) assert dbRes[1:-1] == tgt, 'bad bits returned: %s != %s' % (str(dbRes[1:-1]), str(tgt)) d = None self.conn = None if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/DataStructs/UnitTestBitEnsemble.py", "copies": "11", "size": "4181", "license": "bsd-3-clause", "hash": 4761375225358302000, "line_mean": 28.6524822695, "line_max": 95, "alpha_frac": 0.6048792155, "autogenerated": false, "ratio": 3.0209537572254335, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9125832972725434, "avg_score": null, "num_lines": null }
"""unit testing code for fingerprinting """ import unittest from rdkit import Chem from rdkit import DataStructs def feq(v1,v2,tol=1e-4): return abs(v1-v2)<=tol class TestCase(unittest.TestCase): def setUp(self): #print '\n%s: '%self.shortDescription(), pass def test1(self): # FIX: test HashAtom pass def test2(self): # FIX: test HashBond pass def test3(self): # FIX: test HashPath pass def test4(self): """ check containing mols, no Hs, no valence """ tgts = [ ('CCC(O)C(=O)O', ('CCC','OCC','OCC=O','OCCO','CCCC','OC=O','CC(O)C')), ] for smi,matches in tgts: m = Chem.MolFromSmiles(smi) fp1 = Chem.RDKFingerprint(m,2,7,9192,4,0) obs = fp1.GetOnBits() for match in matches: m2 = Chem.MolFromSmiles(match) fp2 = Chem.RDKFingerprint(m2,2,7,9192,4,0) v1,v2 = DataStructs.OnBitProjSimilarity(fp2,fp1) assert feq(v1,1.0000),'substruct %s not properly contained in %s'%(match,smi) def test5(self): """ check containing mols, use Hs, no valence """ tgts = [ ('CCC(O)C(=O)O', ('O[CH-][CH2-]','O[CH-][C-]=O')), ] for smi,matches in tgts: m = Chem.MolFromSmiles(smi) fp1 = Chem.RDKFingerprint(m,2,7,9192,4,1) obs = fp1.GetOnBits() for match in matches: m2 = Chem.MolFromSmiles(match) fp2 = Chem.RDKFingerprint(m2,2,7,9192,4,1) v1,v2 = DataStructs.OnBitProjSimilarity(fp2,fp1) assert feq(v1,1.0000),'substruct %s not properly contained in %s'%(match,smi) def test6(self): """ check that the bits in a signature of size N which has been folded in half are the same as those in a signature of size N/2 """ smis = [ 'CCC(O)C(=O)O','c1ccccc1','C1CCCCC1','C1NCCCC1','CNCNCNC'] for smi in smis: m = Chem.MolFromSmiles(smi) fp1 = Chem.RDKFingerprint(m,2,7,4096) fp2 = DataStructs.FoldFingerprint(fp1,2) fp3 = Chem.RDKFingerprint(m,2,7,2048) assert tuple(fp2.GetOnBits())==tuple(fp3.GetOnBits()) fp2 = DataStructs.FoldFingerprint(fp2,2) fp3 = Chem.RDKFingerprint(m,2,7,1024) assert tuple(fp2.GetOnBits())==tuple(fp3.GetOnBits()) fp2 = DataStructs.FoldFingerprint(fp1,4) assert tuple(fp2.GetOnBits())==tuple(fp3.GetOnBits()) if __name__ == '__main__': unittest.main()
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/Fingerprints/UnitTestFingerprints.py", "copies": "6", "size": "2703", "license": "bsd-3-clause", "hash": -5907833499856262000, "line_mean": 28.064516129, "line_max": 85, "alpha_frac": 0.6141324454, "autogenerated": false, "ratio": 2.7923553719008263, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6406487817300826, "avg_score": null, "num_lines": null }
"""unit testing code for fingerprinting """ import unittest from rdkit import Chem from rdkit import DataStructs class TestCase(unittest.TestCase): def test1(self): # FIX: test HashAtom pass def test2(self): # FIX: test HashBond pass def test3(self): # FIX: test HashPath pass def test4(self): """ check containing mols, no Hs, no valence """ tgts = [('CCC(O)C(=O)O', ('CCC', 'OCC', 'OCC=O', 'OCCO', 'CCCC', 'OC=O', 'CC(O)C')), ] for smi, matches in tgts: m = Chem.MolFromSmiles(smi) fp1 = Chem.RDKFingerprint(m, 2, 7, 9192, 4, 0) _ = fp1.GetOnBits() for match in matches: m2 = Chem.MolFromSmiles(match) fp2 = Chem.RDKFingerprint(m2, 2, 7, 9192, 4, 0) v1, _ = DataStructs.OnBitProjSimilarity(fp2, fp1) self.assertAlmostEqual(v1, 1, 'substruct %s not properly contained in %s' % (match, smi)) def test5(self): """ check containing mols, use Hs, no valence """ tgts = [('CCC(O)C(=O)O', ('O[CH-][CH2-]', 'O[CH-][C-]=O')), ] for smi, matches in tgts: m = Chem.MolFromSmiles(smi) fp1 = Chem.RDKFingerprint(m, 2, 7, 9192, 4, 1) _ = fp1.GetOnBits() for match in matches: m2 = Chem.MolFromSmiles(match) fp2 = Chem.RDKFingerprint(m2, 2, 7, 9192, 4, 1) v1, _ = DataStructs.OnBitProjSimilarity(fp2, fp1) self.assertAlmostEqual(v1, 1, 'substruct %s not properly contained in %s' % (match, smi)) def test6(self): """ check that the bits in a signature of size N which has been folded in half are the same as those in a signature of size N/2 """ smis = ['CCC(O)C(=O)O', 'c1ccccc1', 'C1CCCCC1', 'C1NCCCC1', 'CNCNCNC'] for smi in smis: m = Chem.MolFromSmiles(smi) fp1 = Chem.RDKFingerprint(m, 2, 7, 4096) fp2 = DataStructs.FoldFingerprint(fp1, 2) fp3 = Chem.RDKFingerprint(m, 2, 7, 2048) self.assertEqual(tuple(fp2.GetOnBits()), tuple(fp3.GetOnBits())) fp2 = DataStructs.FoldFingerprint(fp2, 2) fp3 = Chem.RDKFingerprint(m, 2, 7, 1024) self.assertEqual(tuple(fp2.GetOnBits()), tuple(fp3.GetOnBits())) fp2 = DataStructs.FoldFingerprint(fp1, 4) self.assertEqual(tuple(fp2.GetOnBits()), tuple(fp3.GetOnBits())) if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/Fingerprints/UnitTestFingerprints.py", "copies": "1", "size": "2619", "license": "bsd-3-clause", "hash": -4491740053794908000, "line_mean": 31.7375, "line_max": 97, "alpha_frac": 0.6227567774, "autogenerated": false, "ratio": 2.825242718446602, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39479994958466025, "avg_score": null, "num_lines": null }
"""unit testing code for the DbResultSet object """ from rdkit import RDConfig import unittest,os from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase.DbResultSet import DbResultSet,RandomAccessDbResultSet class TestCase(unittest.TestCase): def setUp(self): self.dbName = RDConfig.RDTestDatabase self.conn = DbConnect(self.dbName) self.curs = self.conn.GetCursor() def test1(self): """ test indexing in, ensure acceptable error conditions """ cmd = 'select * from ten_elements' set = RandomAccessDbResultSet(self.curs,self.conn,cmd) for i in range(12): try: val = set[i] except IndexError: assert i >= 10 def test2(self): """ """ cmd = 'select * from ten_elements' set = RandomAccessDbResultSet(self.curs,self.conn,cmd) assert len(set)==10 for i in range(len(set)): val = set[i] def test3(self): """ """ cmd = 'select * from ten_elements' set = DbResultSet(self.curs,self.conn,cmd) r = [] for thing in set: r.append(thing) assert len(r)==10 def test4(self): """ """ cmd = 'select * from ten_elements_dups' set = DbResultSet(self.curs,self.conn,cmd,removeDups=0) r = [] for thing in set: r.append(thing) assert len(r)==10 def test5(self): """ """ cmd='select * from ten_elements_dups' set = RandomAccessDbResultSet(self.curs,self.conn,cmd,removeDups=0) assert len(set)==10 for i in range(len(set)): val = set[i] def test6(self): """ """ cmd = 'select * from ten_elements_dups' set = DbResultSet(self.curs,self.conn,cmd,removeDups=0) r = [] for thing in set: r.append(thing) assert len(r)==10 if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Dbase/UnitTestDbResultSet.py", "copies": "1", "size": "2115", "license": "bsd-3-clause", "hash": 3780850110058156000, "line_mean": 23.3103448276, "line_max": 71, "alpha_frac": 0.6226950355, "autogenerated": false, "ratio": 3.3150470219435735, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44377420574435733, "avg_score": null, "num_lines": null }
"""unit testing code for the lazy signature generator """ import unittest from rdkit import Chem from rdkit.Chem.Pharm2D import SigFactory,LazyGenerator class TestCase(unittest.TestCase): def setUp(self): self.factory = SigFactory.SigFactory() self.factory.SetPatternsFromSmarts(['O','N']) self.factory.SetBins([(0,2),(2,5),(5,8)]) self.factory.SetMinCount(2) self.factory.SetMaxCount(3) def test1(self): """ simple tests """ mol = Chem.MolFromSmiles('OCC(=O)CCCN') sig = self.factory.GetSignature() assert sig.GetSize()==105,'bad signature size: %d'%(sig.GetSize()) sig.SetIncludeBondOrder(0) gen = LazyGenerator.Generator(sig,mol) assert len(gen) == sig.GetSize(),'length mismatch %d!=%d'%(len(gen),sig.GetSize()) tgt = (1,5,48) for bit in tgt: assert gen[bit],'bit %d not properly set'%(bit) assert gen.GetBit(bit),'bit %d not properly set'%(bit) assert not gen[bit+50],'bit %d improperly set'%(bit+100) sig = self.factory.GetSignature() assert sig.GetSize()==105,'bad signature size: %d'%(sig.GetSize()) sig.SetIncludeBondOrder(1) gen = LazyGenerator.Generator(sig,mol) assert len(gen) == sig.GetSize(),'length mismatch %d!=%d'%(len(gen),sig.GetSize()) tgt = (1,4,5,45) for bit in tgt: assert gen[bit],'bit %d not properly set'%(bit) assert gen.GetBit(bit),'bit %d not properly set'%(bit) assert not gen[bit+50],'bit %d improperly set'%(bit+100) try: gen[sig.GetSize()+1] except IndexError: ok = 1 else: ok = 0 assert ok,'accessing bogus bit did not fail' try: gen[-1] except IndexError: ok = 1 else: ok = 0 assert ok,'accessing bogus bit did not fail' if __name__ == '__main__': unittest.main()
{ "repo_name": "strets123/rdkit", "path": "rdkit/Chem/Pharm2D/UnitTestLazyGenerator.py", "copies": "6", "size": "2115", "license": "bsd-3-clause", "hash": -5332116773116400000, "line_mean": 28.375, "line_max": 86, "alpha_frac": 0.6382978723, "autogenerated": false, "ratio": 3.2790697674418605, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.691736763974186, "avg_score": null, "num_lines": null }
"""unit testing code for the Smiles file handling stuff """ import unittest,sys,os from rdkit import RDConfig from rdkit import Chem from rdkit.six import next class TestCase(unittest.TestCase): def setUp(self): self.smis = ['CC','CCC','CCCCC','CCCCCC','CCCCCCC','CC','CCCCOC'] def test1LazyReader(self): " tests lazy reads """ supp = Chem.SmilesMolSupplierFromText('\n'.join(self.smis),',',0,-1,0) for i in range(4): m = next(supp) assert m,'read %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i i = len(supp)-1 m = supp[i] assert m,'read %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i ms = [x for x in supp] for i in range(len(supp)): m = ms[i] if m: ms[i] = Chem.MolToSmiles(m) l = len(supp) assert l == len(self.smis),'bad supplier length: %d'%(l) i = len(self.smis)-3 m = supp[i-1] assert m,'back index %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i with self.assertRaisesRegexp(Exception, ""): m = supp[len(self.smis)] # out of bound read must fail def test2LazyIter(self): " tests lazy reads using the iterator interface " supp = Chem.SmilesMolSupplierFromText('\n'.join(self.smis),',',0,-1,0) nDone = 0 for mol in supp: assert mol,'read %d failed'%nDone assert mol.GetNumAtoms(),'no atoms in mol %d'%nDone nDone += 1 assert nDone==len(self.smis),'bad number of molecules' l = len(supp) assert l == len(self.smis),'bad supplier length: %d'%(l) i = len(self.smis)-3 m = supp[i-1] assert m,'back index %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i with self.assertRaisesRegexp(Exception, ""): m = supp[len(self.smis)] # out of bound read must not fail def test3BoundaryConditions(self): smis = ['CC','CCOC','fail','CCO'] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis),',',0,-1,0) self.assertEqual(len(supp), 4) self.assertIs(supp[2], None) self.assertTrue(supp[3]) supp = Chem.SmilesMolSupplierFromText('\n'.join(smis),',',0,-1,0) self.assertIs(supp[2], None) self.assertTrue(supp[3]) self.assertEqual(len(supp), 4) with self.assertRaisesRegexp(Exception, ""): supp[4] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis),',',0,-1,0) self.assertEqual(len(supp), 4) self.assertTrue(supp[3]) with self.assertRaisesRegexp(Exception, ""): supp[4] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis),',',0,-1,0) with self.assertRaisesRegexp(Exception, ""): supp[4] self.assertEqual(len(supp), 4) self.assertTrue(supp[3]) if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/Suppliers/UnitTestSmilesMolSupplier.py", "copies": "1", "size": "3033", "license": "bsd-3-clause", "hash": -3372253286232480300, "line_mean": 27.6132075472, "line_max": 74, "alpha_frac": 0.6274315859, "autogenerated": false, "ratio": 3.09805924412666, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9060556207279133, "avg_score": 0.03298692454950515, "num_lines": 106 }
"""unit testing code for the Smiles file handling stuff """ import unittest, sys, os from rdkit import RDConfig from rdkit import Chem from rdkit.six import next class TestCase(unittest.TestCase): def setUp(self): self.smis = ['CC', 'CCC', 'CCCCC', 'CCCCCC', 'CCCCCCC', 'CC', 'CCCCOC'] def test1LazyReader(self): " tests lazy reads " "" supp = Chem.SmilesMolSupplierFromText('\n'.join(self.smis), ',', 0, -1, 0) for i in range(4): m = next(supp) assert m, 'read %d failed' % i assert m.GetNumAtoms(), 'no atoms in mol %d' % i i = len(supp) - 1 m = supp[i] assert m, 'read %d failed' % i assert m.GetNumAtoms(), 'no atoms in mol %d' % i ms = [x for x in supp] for i in range(len(supp)): m = ms[i] if m: ms[i] = Chem.MolToSmiles(m) l = len(supp) assert l == len(self.smis), 'bad supplier length: %d' % (l) i = len(self.smis) - 3 m = supp[i - 1] assert m, 'back index %d failed' % i assert m.GetNumAtoms(), 'no atoms in mol %d' % i with self.assertRaisesRegexp(Exception, ""): m = supp[len(self.smis)] # out of bound read must fail def test2LazyIter(self): " tests lazy reads using the iterator interface " supp = Chem.SmilesMolSupplierFromText('\n'.join(self.smis), ',', 0, -1, 0) nDone = 0 for mol in supp: assert mol, 'read %d failed' % nDone assert mol.GetNumAtoms(), 'no atoms in mol %d' % nDone nDone += 1 assert nDone == len(self.smis), 'bad number of molecules' l = len(supp) assert l == len(self.smis), 'bad supplier length: %d' % (l) i = len(self.smis) - 3 m = supp[i - 1] assert m, 'back index %d failed' % i assert m.GetNumAtoms(), 'no atoms in mol %d' % i with self.assertRaisesRegexp(Exception, ""): m = supp[len(self.smis)] # out of bound read must not fail def test3BoundaryConditions(self): smis = ['CC', 'CCOC', 'fail', 'CCO'] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis), ',', 0, -1, 0) self.assertEqual(len(supp), 4) self.assertIs(supp[2], None) self.assertTrue(supp[3]) supp = Chem.SmilesMolSupplierFromText('\n'.join(smis), ',', 0, -1, 0) self.assertIs(supp[2], None) self.assertTrue(supp[3]) self.assertEqual(len(supp), 4) with self.assertRaisesRegexp(Exception, ""): supp[4] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis), ',', 0, -1, 0) self.assertEqual(len(supp), 4) self.assertTrue(supp[3]) with self.assertRaisesRegexp(Exception, ""): supp[4] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis), ',', 0, -1, 0) with self.assertRaisesRegexp(Exception, ""): supp[4] self.assertEqual(len(supp), 4) self.assertTrue(supp[3]) if __name__ == '__main__': unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Suppliers/UnitTestSmilesMolSupplier.py", "copies": "1", "size": "3112", "license": "bsd-3-clause", "hash": -1082868226116014700, "line_mean": 28.6380952381, "line_max": 78, "alpha_frac": 0.611503856, "autogenerated": false, "ratio": 3.047992164544564, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4159496020544564, "avg_score": null, "num_lines": null }
"""unit testing code for the Smiles file handling stuff """ import unittest,sys,os from rdkit import RDConfig from rdkit import Chem class TestCase(unittest.TestCase): def setUp(self): self.smis = ['CC','CCC','CCCCC','CCCCCC','CCCCCCC','CC','CCCCOC'] def test1LazyReader(self): " tests lazy reads """ supp = Chem.SmilesMolSupplierFromText('\n'.join(self.smis),',',0,-1,0) for i in range(4): m = supp.next() assert m,'read %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i i = len(supp)-1 m = supp[i] assert m,'read %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i ms = [x for x in supp] for i in range(len(supp)): m = ms[i] if m: ms[i] = Chem.MolToSmiles(m) l = len(supp) assert l == len(self.smis),'bad supplier length: %d'%(l) i = len(self.smis)-3 m = supp[i-1] assert m,'back index %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i try: m = supp[len(self.smis)] except: fail = 1 else: fail = 0 assert fail,'out of bound read did not fail' def test2LazyIter(self): " tests lazy reads using the iterator interface " supp = Chem.SmilesMolSupplierFromText('\n'.join(self.smis),',',0,-1,0) nDone = 0 for mol in supp: assert mol,'read %d failed'%i assert mol.GetNumAtoms(),'no atoms in mol %d'%i nDone += 1 assert nDone==len(self.smis),'bad number of molecules' l = len(supp) assert l == len(self.smis),'bad supplier length: %d'%(l) i = len(self.smis)-3 m = supp[i-1] assert m,'back index %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i try: m = supp[len(self.smis)] except: fail = 1 else: fail = 0 assert fail,'out of bound read did not fail' def test3BoundaryConditions(self): smis = ['CC','CCOC','fail','CCO'] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis),',',0,-1,0) assert len(supp)==4 assert supp[2] is None assert supp[3] supp = Chem.SmilesMolSupplierFromText('\n'.join(smis),',',0,-1,0) assert supp[2] is None assert supp[3] assert len(supp)==4 try: supp[4] except: ok=1 else: ok=0 assert ok supp = Chem.SmilesMolSupplierFromText('\n'.join(smis),',',0,-1,0) assert len(supp)==4 assert supp[3] try: supp[4] except: ok=1 else: ok=0 assert ok supp = Chem.SmilesMolSupplierFromText('\n'.join(smis),',',0,-1,0) try: supp[4] except: ok=1 else: ok=0 assert ok assert len(supp)==4 assert supp[3] if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Suppliers/UnitTestSmilesMolSupplier.py", "copies": "2", "size": "3020", "license": "bsd-3-clause", "hash": 9216281417305652000, "line_mean": 22.0534351145, "line_max": 74, "alpha_frac": 0.5860927152, "autogenerated": false, "ratio": 3.041289023162135, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9404578386085575, "avg_score": 0.04456067045531203, "num_lines": 131 }
"""basic unit testing code for atoms """ import unittest from rdkit import Chem class TestCase(unittest.TestCase): def setUp(self): #print '\n%s: '%self.shortDescription(), self.m = Chem.MolFromSmiles('CC(=O)CCSC') def test1Implicit(self): " testing ImplicitValence " a = self.m.GetAtoms()[0] iV = a.GetImplicitValence() assert iV == 3 assert self.m.GetAtomWithIdx(1).GetImplicitValence() == 0 assert self.m.GetAtomWithIdx(2).GetImplicitValence() == 0 assert self.m.GetAtomWithIdx(3).GetImplicitValence() == 2 def test2BondIter(self): " testing bond iteration " a = self.m.GetAtomWithIdx(1) bs = a.GetBonds() r = [] for b in bs: r.append(b) assert len(r) == 3 def test3GetBond(self): " testing GetBondBetweenAtoms(idx,idx) " b = self.m.GetBondBetweenAtoms(1, 2) assert b.GetBondType() == Chem.BondType.DOUBLE, 'GetBond failed' def test4Props(self): " testing atomic props " a = self.m.GetAtomWithIdx(1) assert a.GetSymbol() == 'C' assert a.GetAtomicNum() == 6 assert a.GetFormalCharge() == 0 assert a.GetDegree() == 3 assert a.GetImplicitValence() == 0 assert a.GetExplicitValence() == 4 def test5Setters(self): " testing setting atomic props " a = Chem.Atom(6) assert a.GetSymbol() == 'C' assert a.GetAtomicNum() == 6 a.SetFormalCharge(1) assert a.GetFormalCharge() == 1 try: a.GetImplicitValence() except RuntimeError: ok = 1 else: ok = 0 assert ok if __name__ == '__main__': unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/UnitTestChemAtom.py", "copies": "12", "size": "1868", "license": "bsd-3-clause", "hash": 6462359252787914000, "line_mean": 24.2432432432, "line_max": 68, "alpha_frac": 0.6407922912, "autogenerated": false, "ratio": 3.03739837398374, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.967819066518374, "avg_score": null, "num_lines": null }
from __future__ import print_function try: from reportlab import platypus except ImportError: import sys sys.stderr.write('ReportLab module could not be imported. Db->PDF functionality not available') GetReportlabTable = None QuickReport = None else: from rdkit import Chem try: from pyRDkit.utils import chemdraw except ImportError: hasCDX = 0 else: hasCDX = 1 from rdkit.utils import cactvs from rdkit.Chem import rdDepictor from rdkit.Chem.Draw import DrawUtils from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbInfo from rdkit.Reports.PDFReport import PDFReport, ReportUtils from rdkit.sping.ReportLab.pidReportLab import RLCanvas as Canvas from rdkit.Chem.Draw.MolDrawing import MolDrawing, DrawingOptions from reportlab.lib import colors from reportlab.lib.units import inch import sys def GetReportlabTable(self, *args, **kwargs): """ this becomes a method of DbConnect """ dbRes = self.GetData(*args, **kwargs) rawD = [dbRes.GetColumnNames()] colTypes = dbRes.GetColumnTypes() binCols = [] for i in range(len(colTypes)): if colTypes[i] in DbInfo.sqlBinTypes or colTypes[i] == 'binary': binCols.append(i) nRows = 0 for entry in dbRes: nRows += 1 for col in binCols: entry = list(entry) entry[col] = 'N/A' rawD.append(entry) res = platypus.Table(rawD) return res class CDXImageTransformer(object): def __init__(self, smiCol, width=1, verbose=1, tempHandler=None): self.smiCol = smiCol if tempHandler is None: tempHandler = ReportUtils.TempFileHandler() self.tempHandler = tempHandler self.width = width * inch self.verbose = verbose def __call__(self, arg): res = list(arg) if self.verbose: print('Render:', res[0]) if hasCDX: smi = res[self.smiCol] tmpName = self.tempHandler.get('.jpg') try: img = chemdraw.SmilesToPilImage(smi) w, h = img.size aspect = float(h) / w img.save(tmpName) img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect * self.width res[self.smiCol] = img except Exception: import traceback traceback.print_exc() res[self.smiCol] = 'Failed' return res class CactvsImageTransformer(object): def __init__(self, smiCol, width=1., verbose=1, tempHandler=None): self.smiCol = smiCol if tempHandler is None: tempHandler = ReportUtils.TempFileHandler() self.tempHandler = tempHandler self.width = width * inch self.verbose = verbose def __call__(self, arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n' % (self.smiCol, str(res[0]))) smi = res[self.smiCol] tmpName = self.tempHandler.get('.gif') aspect = 1 width = 300 height = aspect * width ok = cactvs.SmilesToGif(smi, tmpName, (width, height)) if ok: try: img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect * self.width except Exception: ok = 0 if ok: res[self.smiCol] = img else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res class ReportLabImageTransformer(object): def __init__(self, smiCol, width=1., verbose=1, tempHandler=None): self.smiCol = smiCol self.width = width * inch self.verbose = verbose def __call__(self, arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n' % (self.smiCol, str(res[0]))) smi = res[self.smiCol] aspect = 1 width = self.width height = aspect * width try: mol = Chem.MolFromSmiles(smi) Chem.Kekulize(mol) canv = Canvas((width, height)) options = DrawingOptions() options.atomLabelMinFontSize = 3 options.bondLineWidth = 0.5 drawing = MolDrawing(options=options) if not mol.GetNumConformers(): rdDepictor.Compute2DCoords(mol) drawing.AddMol(mol, canvas=canv) ok = True except Exception: if self.verbose: import traceback traceback.print_exc() ok = False if ok: res[self.smiCol] = canv.drawing else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res class RDImageTransformer(object): def __init__(self, smiCol, width=1., verbose=1, tempHandler=None): self.smiCol = smiCol if tempHandler is None: tempHandler = ReportUtils.TempFileHandler() self.tempHandler = tempHandler self.width = width * inch self.verbose = verbose def __call__(self, arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n' % (self.smiCol, str(res[0]))) smi = res[self.smiCol] tmpName = self.tempHandler.get('.jpg') aspect = 1 width = 300 height = aspect * width ok = DrawUtils.SmilesToJpeg(smi, tmpName, size=(width, height)) if ok: try: img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect * self.width except Exception: ok = 0 if ok: res[self.smiCol] = img else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res def QuickReport(conn, fileName, *args, **kwargs): title = 'Db Report' if 'title' in kwargs: title = kwargs['title'] del kwargs['title'] names = [x.upper() for x in conn.GetColumnNames()] try: smiCol = names.index('SMILES') except ValueError: try: smiCol = names.index('SMI') except ValueError: smiCol = -1 if smiCol > -1: if hasCDX: tform = CDXImageTransformer(smiCol) elif 1: tform = ReportLabImageTransformer(smiCol) else: tform = CactvsImageTransformer(smiCol) else: tform = None kwargs['transform'] = tform tbl = conn.GetReportlabTable(*args, **kwargs) tbl.setStyle( platypus.TableStyle([('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONT', (0, 0), (-1, -1), 'Times-Roman', 8), ])) if smiCol > -1 and tform: tbl._argW[smiCol] = tform.width * 1.2 elements = [tbl] reportTemplate = PDFReport() reportTemplate.pageHeader = title doc = platypus.SimpleDocTemplate(fileName) doc.build(elements, onFirstPage=reportTemplate.onPage, onLaterPages=reportTemplate.onPage) DbConnect.GetReportlabTable = GetReportlabTable if __name__ == '__main__': dbName = sys.argv[1] tblName = sys.argv[2] fName = 'report.pdf' conn = DbConnect(dbName, tblName) QuickReport(conn, fName, where="where mol_id in ('1','100','104','107')")
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Dbase/DbReport.py", "copies": "4", "size": "7344", "license": "bsd-3-clause", "hash": -4693990109312630000, "line_mean": 28.8536585366, "line_max": 98, "alpha_frac": 0.6107026144, "autogenerated": false, "ratio": 3.4625176803394626, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.021081300847869935, "num_lines": 246 }
from __future__ import print_function try: from reportlab import platypus except ImportError: import sys sys.stderr.write('ReportLab module could not be imported. Db->PDF functionality not available') GetReportlabTable = None QuickReport = None else: from rdkit import Chem try: from pyRDkit.utils import chemdraw except ImportError: hasCDX = 0 else: hasCDX = 1 from rdkit.utils import cactvs from rdkit.Chem import rdDepictor from rdkit.Chem.Draw import DrawUtils from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbInfo from rdkit.Reports.PDFReport import PDFReport, ReportUtils import os, tempfile, sys def GetReportlabTable(self, *args, **kwargs): """ this becomes a method of DbConnect """ dbRes = self.GetData(*args, **kwargs) rawD = [dbRes.GetColumnNames()] colTypes = dbRes.GetColumnTypes() binCols = [] for i in range(len(colTypes)): if colTypes[i] in DbInfo.sqlBinTypes or colTypes[i] == 'binary': binCols.append(i) nRows = 0 for entry in dbRes: nRows += 1 for col in binCols: entry = list(entry) entry[col] = 'N/A' rawD.append(entry) #if nRows >10: break res = platypus.Table(rawD) return res from reportlab.lib.units import inch class CDXImageTransformer(object): def __init__(self, smiCol, width=1, verbose=1, tempHandler=None): self.smiCol = smiCol if tempHandler is None: tempHandler = ReportUtils.TempFileHandler() self.tempHandler = tempHandler self.width = width * inch self.verbose = verbose def __call__(self, arg): res = list(arg) if self.verbose: print('Render:', res[0]) if hasCDX: smi = res[self.smiCol] tmpName = self.tempHandler.get('.jpg') try: img = chemdraw.SmilesToPilImage(smi) w, h = img.size aspect = float(h) / w img.save(tmpName) img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect * self.width res[self.smiCol] = img except Exception: import traceback traceback.print_exc() res[self.smiCol] = 'Failed' return res class CactvsImageTransformer(object): def __init__(self, smiCol, width=1., verbose=1, tempHandler=None): self.smiCol = smiCol if tempHandler is None: tempHandler = ReportUtils.TempFileHandler() self.tempHandler = tempHandler self.width = width * inch self.verbose = verbose def __call__(self, arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n' % (self.smiCol, str(res[0]))) smi = res[self.smiCol] tmpName = self.tempHandler.get('.gif') aspect = 1 width = 300 height = aspect * width ok = cactvs.SmilesToGif(smi, tmpName, (width, height)) if ok: try: img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect * self.width except Exception: ok = 0 if ok: res[self.smiCol] = img else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res from rdkit.sping.ReportLab.pidReportLab import RLCanvas as Canvas from rdkit.Chem.Draw.MolDrawing import MolDrawing, DrawingOptions class ReportLabImageTransformer(object): def __init__(self, smiCol, width=1., verbose=1, tempHandler=None): self.smiCol = smiCol self.width = width * inch self.verbose = verbose def __call__(self, arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n' % (self.smiCol, str(res[0]))) smi = res[self.smiCol] aspect = 1 width = self.width height = aspect * width try: mol = Chem.MolFromSmiles(smi) Chem.Kekulize(mol) canv = Canvas((width, height)) options = DrawingOptions() options.atomLabelMinFontSize = 3 options.bondLineWidth = 0.5 drawing = MolDrawing(options=options) if not mol.GetNumConformers(): rdDepictor.Compute2DCoords(mol) drawing.AddMol(mol, canvas=canv) ok = True except Exception: if self.verbose: import traceback traceback.print_exc() ok = False if ok: res[self.smiCol] = canv.drawing else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res class RDImageTransformer(object): def __init__(self, smiCol, width=1., verbose=1, tempHandler=None): self.smiCol = smiCol if tempHandler is None: tempHandler = ReportUtils.TempFileHandler() self.tempHandler = tempHandler self.width = width * inch self.verbose = verbose def __call__(self, arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n' % (self.smiCol, str(res[0]))) smi = res[self.smiCol] tmpName = self.tempHandler.get('.jpg') aspect = 1 width = 300 height = aspect * width ok = DrawUtils.SmilesToJpeg(smi, tmpName, size=(width, height)) if ok: try: img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect * self.width except Exception: ok = 0 if ok: res[self.smiCol] = img else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res def QuickReport(conn, fileName, *args, **kwargs): from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch styles = getSampleStyleSheet() title = 'Db Report' if kwargs.has_key('title'): title = kwargs['title'] del kwargs['title'] names = [x.upper() for x in conn.GetColumnNames()] try: smiCol = names.index('SMILES') except ValueError: try: smiCol = names.index('SMI') except ValueError: smiCol = -1 if smiCol > -1: if hasCDX: tform = CDXImageTransformer(smiCol) elif 1: tform = ReportLabImageTransformer(smiCol) else: tform = CactvsImageTransformer(smiCol) else: tform = None kwargs['transform'] = tform tbl = conn.GetReportlabTable(*args, **kwargs) tbl.setStyle( platypus.TableStyle([('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONT', (0, 0), (-1, -1), 'Times-Roman', 8), ])) if smiCol > -1 and tform: tbl._argW[smiCol] = tform.width * 1.2 elements = [tbl] reportTemplate = PDFReport() reportTemplate.pageHeader = title doc = platypus.SimpleDocTemplate(fileName) doc.build(elements, onFirstPage=reportTemplate.onPage, onLaterPages=reportTemplate.onPage) DbConnect.GetReportlabTable = GetReportlabTable if __name__ == '__main__': import sys dbName = sys.argv[1] tblName = sys.argv[2] fName = 'report.pdf' conn = DbConnect(dbName, tblName) QuickReport(conn, fName, where="where mol_id in ('1','100','104','107')")
{ "repo_name": "jandom/rdkit", "path": "rdkit/Dbase/DbReport.py", "copies": "1", "size": "7541", "license": "bsd-3-clause", "hash": 9116067528467865000, "line_mean": 28.8063241107, "line_max": 98, "alpha_frac": 0.6133138841, "autogenerated": false, "ratio": 3.478321033210332, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9486164033354745, "avg_score": 0.02109417679111748, "num_lines": 253 }
from rdkit import RDConfig if hasattr(RDConfig,"usePgSQL") and RDConfig.usePgSQL: from pyPgSQL import PgSQL # as of this writing (March 2004), this results in a speedup in # getting results back from the wrapper: PgSQL.fetchReturnsList=1 from pyPgSQL.PgSQL import * sqlTextTypes = [PG_CHAR,PG_BPCHAR,PG_TEXT,PG_VARCHAR,PG_NAME] sqlIntTypes = [PG_INT8,PG_INT2,PG_INT4] sqlFloatTypes = [PG_FLOAT4,PG_FLOAT8] sqlBinTypes = [PG_OID,PG_BLOB,PG_BYTEA] getTablesSql = """select tablename from pg_tables where schemaname='public'""" getTablesAndViewsSql = """SELECT c.relname as "Name" FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r','v','S','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid) """ getDbSql = """ select datname from pg_database where datallowconn """ fileWildcard=None placeHolder='%s' binaryTypeName="bytea" binaryHolder = PgBytea RDTestDatabase="::RDTests" elif hasattr(RDConfig,"useSqlLite") and RDConfig.useSqlLite: try: import sqlite3 as sqlite #from sqlite3 import * except ImportError: from pysqlite2 import dbapi2 as sqlite #from pysqlite2 import * sqlTextTypes = [] sqlIntTypes = [] sqlFloatTypes = [] sqlBinTypes = [] getTablesSql = """select name from SQLite_Master where type='table'""" getTablesAndViewsSql = """select name from SQLite_Master where type in ('table','view')""" getDbSql = None dbFileWildcard='*.sqlt' placeHolder='?' binaryTypeName="blob" binaryHolder = buffer connect = lambda x,*args:sqlite.connect(x) else: raise ImportError,"Neither sqlite nor PgSQL support found."
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Dbase/DbModule.py", "copies": "2", "size": "2081", "license": "bsd-3-clause", "hash": 1634136791542979800, "line_mean": 33.1147540984, "line_max": 92, "alpha_frac": 0.7025468525, "autogenerated": false, "ratio": 3.2566510172143976, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4959197869714398, "avg_score": null, "num_lines": null }
from rdkit import six from rdkit import RDConfig if hasattr(RDConfig,"usePgSQL") and RDConfig.usePgSQL: from pyPgSQL import PgSQL # as of this writing (March 2004), this results in a speedup in # getting results back from the wrapper: PgSQL.fetchReturnsList=1 from pyPgSQL.PgSQL import * sqlTextTypes = [PG_CHAR,PG_BPCHAR,PG_TEXT,PG_VARCHAR,PG_NAME] sqlIntTypes = [PG_INT8,PG_INT2,PG_INT4] sqlFloatTypes = [PG_FLOAT4,PG_FLOAT8] sqlBinTypes = [PG_OID,PG_BLOB,PG_BYTEA] getTablesSql = """select tablename from pg_tables where schemaname='public'""" getTablesAndViewsSql = """SELECT c.relname as "Name" FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r','v','S','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid) """ getDbSql = """ select datname from pg_database where datallowconn """ fileWildcard=None placeHolder='%s' binaryTypeName="bytea" binaryHolder = PgBytea RDTestDatabase="::RDTests" elif hasattr(RDConfig,"useSqlLite") and RDConfig.useSqlLite: try: import sqlite3 as sqlite #from sqlite3 import * except ImportError: from pysqlite2 import dbapi2 as sqlite #from pysqlite2 import * sqlTextTypes = [] sqlIntTypes = [] sqlFloatTypes = [] sqlBinTypes = [] getTablesSql = """select name from SQLite_Master where type='table'""" getTablesAndViewsSql = """select name from SQLite_Master where type in ('table','view')""" getDbSql = None dbFileWildcard='*.sqlt' placeHolder='?' binaryTypeName="blob" binaryHolder = memoryview if six.PY3 else buffer connect = lambda x,*args:sqlite.connect(x) else: raise ImportError("Neither sqlite nor PgSQL support found.")
{ "repo_name": "soerendip42/rdkit", "path": "rdkit/Dbase/DbModule.py", "copies": "4", "size": "2131", "license": "bsd-3-clause", "hash": -681594176932317000, "line_mean": 33.3709677419, "line_max": 92, "alpha_frac": 0.7048334115, "autogenerated": false, "ratio": 3.26840490797546, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.597323831947546, "avg_score": null, "num_lines": null }
from xml.etree import ElementTree # check the version of ElementTree. We need at least version 1.2 # in order for the XPath-style parsing stuff to work import re vers = re.split("[a-zA-Z]",ElementTree.VERSION)[0] if vers < '1.2': raise ImportError,'The PubMed record interface requires a version of ElementTree >= 1.2' class Record(object): def __init__(self,element): for field in self._fieldsOfInterest: setattr(self,field,'') self._element = element def toXML(self): from cStringIO import StringIO sio = StringIO() ElementTree.ElementTree(self._element).write(sio) return sio.getvalue() class SummaryRecord(Record): _fieldsOfInterest=['PubMedId','PubDate','Source','Authors', 'Title','Volume','Issue','Pages','Lang', 'HasAbstract','RecordStatus'] def __init__(self,element): Record.__init__(self,element) for item in element.getiterator('Item'): if item.attrib['Name'] in self._fieldsOfInterest: setattr(self,item.attrib['Name'],item.text) if self.PubDate: self.PubYear = str(self.PubDate).split(' ')[0] class JournalArticleRecord(Record): _fieldsOfInterest=['PubMedId','PubYear','Source','Authors', 'Title','Volume','Issue','Pages','Lang', 'Abstract'] def __init__(self,element): Record.__init__(self,element) cite = self._element.find('MedlineCitation') self.PubMedId = cite.findtext('PMID') article = cite.find('Article') issue = article.find('Journal/JournalIssue') self.Volume = issue.findtext('Volume') self.Issue = issue.findtext('Issue') self.PubYear = issue.findtext('PubDate/Year') if not self.PubYear: txt = issue.findtext('PubDate/MedlineDate') self.PubYear = txt.split(' ')[0] self.Title = unicode(article.findtext('ArticleTitle')) self.Pages = article.findtext('Pagination/MedlinePgn') abs = article.findtext('Abstract/AbstractText') if abs: self.Abstract = unicode(abs) self.authors = [] tmp = [] for author in article.find('AuthorList').getiterator('Author'): last = unicode(author.findtext('LastName')) first = unicode(author.findtext('ForeName')) initials = unicode(author.findtext('Initials')) self.authors.append((last,first,initials)) tmp.append('%s %s'%(last,initials)) self.Authors=', '.join(tmp) journal = cite.findtext('MedlineJournalInfo/MedlineTA') if journal: self.Source = unicode(journal) self.ParseKeywords() self.ParseChemicals() def ParseKeywords(self): self.keywords = [] headings = self.find('MedlineCitation/MeshHeadingList') if headings: for heading in headings.getiterator('MeshHeading'): kw = unicode(heading.findtext('DescriptorName')) for qualifier in heading.getiterator('QualifierName'): kw += ' / %s'%(unicode(qualifier.text)) self.keywords.append(kw) def ParseChemicals(self): self.chemicals = [] chemicals = self.find('MedlineCitation/ChemicalList') if chemicals: for chemical in chemicals.getiterator('Chemical'): name = chemical.findtext('NameOfSubstance').encode('utf-8') rn = chemical.findtext('RegistryNumber').encode('utf-8') if rn != '0': self.chemicals.append('%s <%s>'%(name,rn)) else: self.chemicals.append('%s'%(name)) # -------------------------------------------- # # We'll expose these ElementTree methods in case # client code wants to pull extra info # def getiterator(self,key=None): if key is not None: return self._element.getiterator(key) else: return self._element.getiterator() def find(self,key): return self._element.find(key) def findtext(self,key): return self._element.findtext(key) def findall(self,key): return self._element.findall(key) class LinkRecord(Record): _fieldsOfInterest=[] def __init__(self,element): Record.__init__(self,element) self.PubMedId = self._element.text nbr = self._element.get('HasNeighbor','N') if nbr == 'Y': self.HasNeighbor = 1 else: self.HasNeighbor = 0
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Dbase/Pubmed/Records.py", "copies": "2", "size": "4495", "license": "bsd-3-clause", "hash": 3040483159045184500, "line_mean": 32.5447761194, "line_max": 90, "alpha_frac": 0.6418242492, "autogenerated": false, "ratio": 3.598879103282626, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5240703352482626, "avg_score": null, "num_lines": null }
""" functionality for drawing hierarchical catalogs on sping canvases """ from sping import pid as piddle class VisOpts(object): circRad = 10 minCircRad = 4 maxCircRad = 16 circColor = piddle.Color(0.6, 0.6, 0.9) terminalEmptyColor = piddle.Color(.8, .8, .2) terminalOnColor = piddle.Color(0.8, 0.8, 0.8) terminalOffColor = piddle.Color(0.2, 0.2, 0.2) outlineColor = piddle.transparent lineColor = piddle.Color(0, 0, 0) lineWidth = 1 horizOffset = 5 vertOffset = 75 topMargin = 20 labelFont = piddle.Font(face='helvetica', size=10) highlightColor = piddle.Color(1., 1., .4) highlightWidth = 2 visOpts = VisOpts() def GetMinCanvasSize(adjList, levelList): maxAcross = -1 for k in levelList.keys(): nHere = len(levelList[k]) maxAcross = max(maxAcross, nHere) nLevs = len(levelList.keys()) minSize = (maxAcross * (visOpts.minCircRad * 2 + visOpts.horizOffset), visOpts.topMargin + nLevs * visOpts.vertOffset) return minSize def DrawHierarchy(adjList, levelList, canvas, entryColors=None, bitIds=None, minLevel=-1, maxLevel=1e8): """ Arguments: - adjList: adjacency list representation of the hierarchy to be drawn - levelList: dictionary mapping level -> list of ids """ if bitIds is None: bitIds = [] if entryColors is None: entryColors = {} levelLengths = levelList.keys() levelLengths.sort() minLevel = max(minLevel, levelLengths[0]) maxLevel = min(maxLevel, levelLengths[-1]) dims = canvas.size drawLocs = {} # start at the bottom of the hierarchy and work up: for levelLen in range(maxLevel, minLevel - 1, -1): nLevelsDown = levelLen - minLevel pos = [0, visOpts.vertOffset * nLevelsDown + visOpts.topMargin] ids = levelList.get(levelLen, []) # FIX: we'll eventually want to figure out some kind of sorting here: nHere = len(ids) canvas.defaultFont = visOpts.labelFont if nHere: # figure the size of each node at this level: spacePerNode = float(dims[0]) / nHere spacePerNode -= visOpts.horizOffset nodeRad = max(spacePerNode / 2, visOpts.minCircRad) nodeRad = min(nodeRad, visOpts.maxCircRad) spacePerNode = nodeRad * 2 + visOpts.horizOffset # start in the midde of the canvas: pos[0] = dims[0] / 2. # maybe we need to offset a little: if nHere % 2: pos[0] -= spacePerNode / 2 # move to the left by half the number of nodes: pos[0] -= (nHere // 2 - .5) * spacePerNode # Find the locations and draw connectors: for ID in ids: if not bitIds or ID in bitIds: # first do lines down to the next level: if levelLen != maxLevel: for neighbor in adjList[ID]: if neighbor in drawLocs: p2 = drawLocs[neighbor][0] canvas.drawLine(pos[0], pos[1], p2[0], p2[1], visOpts.lineColor, visOpts.lineWidth) drawLocs[ID] = tuple(pos), nodeRad pos[0] += spacePerNode for ID in drawLocs.keys(): pos, nodeRad = drawLocs[ID] x1, y1 = pos[0] - nodeRad, pos[1] - nodeRad x2, y2 = pos[0] + nodeRad, pos[1] + nodeRad drawColor = entryColors.get(ID, visOpts.circColor) canvas.drawEllipse(x1, y1, x2, y2, visOpts.outlineColor, 0, drawColor) label = str(ID) # txtLoc = ( pos[0]-canvas.stringWidth(label)/2, # pos[1]+canvas.fontHeight()/4 ) txtLoc = (pos[0] + canvas.fontHeight() / 4, pos[1] + canvas.stringWidth(label) / 2) canvas.drawString(label, txtLoc[0], txtLoc[1], angle=90) return drawLocs
{ "repo_name": "rvianello/rdkit", "path": "rdkit/DataStructs/HierarchyVis.py", "copies": "5", "size": "3875", "license": "bsd-3-clause", "hash": 1510835844414436600, "line_mean": 30.25, "line_max": 99, "alpha_frac": 0.6459354839, "autogenerated": false, "ratio": 3.1555374592833876, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6301472943183387, "avg_score": null, "num_lines": null }
import bisect class TopNContainer(object): """ maintains a sorted list of a particular number of data elements. """ def __init__(self,size,mostNeg=-1e99): self._size = size self.best = [mostNeg]*self._size self.extras = [None]*self._size def Insert(self,val,extra=None): """ only does the insertion if val fits """ if val > self.best[0]: idx = bisect.bisect(self.best,val) # insert the new element if idx == self._size: self.best.append(val) self.extras.append(extra) else: self.best.insert(idx,val) self.extras.insert(idx,extra) # and pop off the head self.best.pop(0) self.extras.pop(0) def GetPts(self): """ returns our set of points """ return self.best def GetExtras(self): """ returns our set of extras """ return self.extras def __len__(self): return self._size def __getitem__(self,which): return self.best[which],self.extras[which] def reverse(self): self.best.reverse() self.extras.reverse() if __name__ == '__main__': import random pts = [int(100*random.random()) for x in range(10)] c = TopNContainer(4) for pt in pts: c.Insert(pt,extra=str(pt)) print c.GetPts() print c.GetExtras()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/DataStructs/TopNContainer.py", "copies": "1", "size": "1553", "license": "bsd-3-clause", "hash": -8394464511504048000, "line_mean": 24.8833333333, "line_max": 70, "alpha_frac": 0.6258853831, "autogenerated": false, "ratio": 3.368763557483731, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9285420157440427, "avg_score": 0.04184575662866074, "num_lines": 60 }
import copy urlBase="http://eutils.ncbi.nlm.nih.gov/entrez/eutils" searchBase=urlBase+"/esearch.fcgi" summaryBase=urlBase+"/esummary.fcgi" fetchBase=urlBase+"/efetch.fcgi" linkBase=urlBase+"/elink.fcgi" # for links to pubmed web pages: queryBase="http://www.ncbi.nlm.nih.gov/entrez/query.fcgi" _details = { 'db':'pubmed', 'retmode':'xml', 'tool':'RDPMTools', 'email':'[email protected]', } def details(): return copy.copy(_details) # FIX: Allow PMID searches searchableFields={ "Author":("AU","Authors' Name "), "Keyword":("MH","MeSH keyword"), "Substance":("NM","Substance Name"), "Title":("TI","Text from the article title"), "Title/Abstract":("TIAB","Text from the article title and/or abstract"), "Registry Number":("RN","CAS Registry Number"), "Subject":("SB","Pubmed Subject Subset (tox,aids,cancer,bioethics,cam,history,space,systematic)"), "Journal":("TA","Journal Name"), "Year":("DP","Publication Date"), "Affiliation":("AD","Authors' affiliation"), } searchableFieldsOrder=[ "Author", "Keyword", "Title", "Title/Abstract", "Substance", "Registry Number", "Subject", "Journal", "Year", "Affiliation", ]
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Dbase/Pubmed/QueryParams.py", "copies": "3", "size": "1462", "license": "bsd-3-clause", "hash": -1093318081724212900, "line_mean": 25.5818181818, "line_max": 100, "alpha_frac": 0.6751025992, "autogenerated": false, "ratio": 3.0585774058577404, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.523368000505774, "avg_score": null, "num_lines": null }
import os import io import unittest from rdkit import RDConfig from rdkit import Chem from rdkit.Chem import FragmentCatalog, BuildFragmentCatalog from rdkit.six.moves import cPickle def feq(n1,n2,tol=1e-4): return abs(n1-n2)<tol class TestCase(unittest.TestCase): def setUp(self) : self.smiList = ["S(SC1=NC2=CC=CC=C2S1)C3=NC4=C(S3)C=CC=C4","CC1=CC(=O)C=CC1=O", "OC1=C(Cl)C=C(C=C1[N+]([O-])=O)[N+]([O-])=O", "[O-][N+](=O)C1=CNC(=N)S1", "NC1=CC2=C(C=C1)C(=O)C3=C(C=CC=C3)C2=O", "OC(=O)C1=C(C=CC=C1)C2=C3C=CC(=O)C(=C3OC4=C2C=CC(=C4Br)O)Br", "CN(C)C1=C(Cl)C(=O)C2=C(C=CC=C2)C1=O", "CC1=C(C2=C(C=C1)C(=O)C3=CC=CC=C3C2=O)[N+]([O-])=O", "CC(=NO)C(C)=NO"] self.smiList2 = ['OCCC','CCC','C=CC','OC=CC','CC(O)C', 'C=C(O)C','OCCCC','CC(O)CC','C=CCC','CC=CC', 'OC=CCC','CC=C(O)C','OCC=CC','C=C(O)CC', 'C=CC(O)C','C=CCCO', ] self.list2Acts = [1,0,0,1,1,1,1,1,0,0,1,1,1,1,1,1] self.list2Obls = [(0,1,2),(1,3),(1,4,5),(1,6,7),(0,8),(0,6,9),(0,1,2,3,10), (0,1,2,8,11),(1,3,4,5,12),(1,4,5,13),(1,3,6,7,14),(0,1,6,7,9,15)] ffile = os.path.join(RDConfig.RDDataDir,'FunctionalGroups.txt') self.catParams = FragmentCatalog.FragCatParams(1,6,ffile) self.fragCat = FragmentCatalog.FragCatalog(self.catParams) self.fgen = FragmentCatalog.FragCatGenerator() def _fillCat(self,smilList): for smi in self.smiList2: mol = Chem.MolFromSmiles(smi) self.fgen.AddFragsFromMol(mol,self.fragCat) def _testBits(self,fragCat): fpgen = FragmentCatalog.FragFPGenerator() obits = [3,2,3,3,2,3,5,5,5,4,5,6] obls = self.list2Obls suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList2), ',',0,-1,0) i = 0 for mol in suppl: fp = fpgen.GetFPForMol(mol, fragCat) if i < len(obits): smi = Chem.MolToSmiles(mol) assert fp.GetNumOnBits()==obits[i],'%s: %s'%(smi,str(fp.GetOnBits())) obl = fp.GetOnBits() if i < len(obls): assert tuple(obl)==obls[i],'%s: %s'%(smi,obl) i+=1 def test1CatGen(self) : self._fillCat(self.smiList2) assert self.fragCat.GetNumEntries()==21 assert self.fragCat.GetFPLength()==21 self._testBits(self.fragCat) def test2CatStringPickle(self): self._fillCat(self.smiList2) # test non-binary pickle: cat2 = cPickle.loads(cPickle.dumps(self.fragCat)) assert cat2.GetNumEntries()==21 assert cat2.GetFPLength()==21 self._testBits(cat2) # test binary pickle: cat2 = cPickle.loads(cPickle.dumps(self.fragCat,1)) assert cat2.GetNumEntries()==21 assert cat2.GetFPLength()==21 self._testBits(cat2) def test3CatFilePickle(self): with open(os.path.join(RDConfig.RDCodeDir,'Chem', 'test_data','simple_catalog.pkl'), 'r') as pklTFile: buf = pklTFile.read().replace('\r\n', '\n').encode('utf-8') pklTFile.close() with io.BytesIO(buf) as pklFile: cat = cPickle.load(pklFile, encoding='bytes') assert cat.GetNumEntries()==21 assert cat.GetFPLength()==21 self._testBits(cat) def test4CatGuts(self): self._fillCat(self.smiList2) assert self.fragCat.GetNumEntries()==21 assert self.fragCat.GetFPLength()==21 # # FIX: (Issue 162) # bits like 11 and 15 are questionable here because the underlying # fragments are symmetrical, so they can generate one of two # text representations (i.e. there is nothing to distinguish # between 'CC<-O>CC' and 'CCC<-O>C'). # This ought to eventually be cleaned up. descrs = [(0,'C<-O>C',1,(34,)), (1,'CC',1,()), (2,'C<-O>CC',2,(34,)), (3,'CCC',2,()), (4,'C=C',1,()), (5,'C=CC',2,()), (6,'C<-O>=C',1,(34,)), (7,'C<-O>=CC',2,(34,)), (8,'CC<-O>C',2,(34,)), (9,'C=C<-O>C',2,(34,)), (10,'C<-O>CCC',3,(34,)), (11,'CC<-O>CC',3,(34,)), (12,'C=CCC',3,()), (13,'CC=CC',3,()), (14,'C<-O>=CCC',3,(34,)), (15,'CC=C<-O>C',3,(34,)), (16,'C=CC<-O>',2,(34,)), ] for i in range(len(descrs)): id,d,order,ids=descrs[i] descr = self.fragCat.GetBitDescription(id) assert descr == d,'%d: %s != %s'%(id,descr,d) assert self.fragCat.GetBitOrder(id)==order assert tuple(self.fragCat.GetBitFuncGroupIds(id)) == \ ids,'%d: %s != %s'%(id, str(self.fragCat.GetBitFuncGroupIds(id)), str(ids)) def _test5MoreComplex(self): lastIdx = 0 ranges = {} suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList), ',',0,-1,0) i = 0 for mol in suppl: nEnt = self.fgen.AddFragsFromMol(mol,self.fragCat) ranges[i] = range(lastIdx,lastIdx+nEnt) lastIdx+=nEnt i+=1 # now make sure that those bits are contained in the signatures: fpgen = FragmentCatalog.FragFPGenerator() i = 0 for mol in suppl: fp = fpgen.GetFPForMol(mol,self.fragCat) for bit in ranges[i]: assert fp[bit],'%s: %s'%(Chem.MolToSmiles(mol),str(bit)) i += 1 def test6Builder(self): suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList2), ',',0,-1,0) cat = BuildFragmentCatalog.BuildCatalog(suppl,minPath=1,reportFreq=20) assert cat.GetNumEntries()==21 assert cat.GetFPLength()==21 self._testBits(cat) def test7ScoreMolecules(self): suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList2), ',',0,-1,0) cat = BuildFragmentCatalog.BuildCatalog(suppl,minPath=1,reportFreq=20) assert cat.GetNumEntries()==21 assert cat.GetFPLength()==21 scores,obls = BuildFragmentCatalog.ScoreMolecules(suppl,cat,acts=self.list2Acts, reportFreq=20) for i in range(len(self.list2Obls)): assert tuple(obls[i])==self.list2Obls[i],'%d: %s != %s'%(i,str(obls[i]), str(self.list2Obls[i])) scores2 = BuildFragmentCatalog.ScoreFromLists(obls,suppl,cat,acts=self.list2Acts, reportFreq=20) for i in range(len(scores)): assert (scores[i]==scores2[i]).all(),'%d: %s != %s'%(i,str(scores[i]),str(scores2[i])) def test8MolRanks(self): suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList2), ',',0,-1,0) cat = BuildFragmentCatalog.BuildCatalog(suppl,minPath=1,reportFreq=20) assert cat.GetNumEntries()==21 assert cat.GetFPLength()==21 # new InfoGain ranking: bitInfo,fps = BuildFragmentCatalog.CalcGains(suppl,cat,topN=10,acts=self.list2Acts, reportFreq=20,biasList=(1,)) entry = bitInfo[0] assert int(entry[0])==0 assert cat.GetBitDescription(int(entry[0]))=='C<-O>C' assert feq(entry[1],0.4669) entry = bitInfo[1] assert int(entry[0]) in (2,6) txt = cat.GetBitDescription(int(entry[0])) self.assertTrue( txt in ('C<-O>CC','C<-O>=C'), txt) assert feq(entry[1],0.1611) entry = bitInfo[6] assert int(entry[0])==16 assert cat.GetBitDescription(int(entry[0]))=='C=CC<-O>' assert feq(entry[1],0.0560) # standard InfoGain ranking: bitInfo,fps = BuildFragmentCatalog.CalcGains(suppl,cat,topN=10,acts=self.list2Acts, reportFreq=20) entry = bitInfo[0] assert int(entry[0])==0 assert cat.GetBitDescription(int(entry[0]))=='C<-O>C' assert feq(entry[1],0.4669) entry = bitInfo[1] assert int(entry[0])==5 assert cat.GetBitDescription(int(entry[0]))=='C=CC' assert feq(entry[1],0.2057) def test9Issue116(self): smiList = ['Cc1ccccc1'] suppl = Chem.SmilesMolSupplierFromText('\n'.join(smiList), ',',0,-1,0) cat = BuildFragmentCatalog.BuildCatalog(suppl,minPath=2,maxPath=2) assert cat.GetFPLength()==2 assert cat.GetBitDescription(0)=='ccC' fpgen = FragmentCatalog.FragFPGenerator() mol = Chem.MolFromSmiles('Cc1ccccc1') fp = fpgen.GetFPForMol(mol,cat) assert fp[0] assert fp[1] mol = Chem.MolFromSmiles('c1ccccc1-c1ccccc1') fp = fpgen.GetFPForMol(mol,cat) assert not fp[0] assert fp[1] if __name__ == '__main__': unittest.main()
{ "repo_name": "strets123/rdkit", "path": "rdkit/Chem/UnitTestCatalog.py", "copies": "3", "size": "9124", "license": "bsd-3-clause", "hash": -5355344922590387000, "line_mean": 35.7903225806, "line_max": 92, "alpha_frac": 0.5577597545, "autogenerated": false, "ratio": 2.8414824042354407, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9703580067451725, "avg_score": 0.03913241825674311, "num_lines": 248 }
import os import io import unittest from rdkit import RDConfig from rdkit import Chem from rdkit.Chem import FragmentCatalog, BuildFragmentCatalog from rdkit.six.moves import cPickle def feq(n1, n2, tol=1e-4): return abs(n1 - n2) < tol class TestCase(unittest.TestCase): def setUp(self): self.smiList = ["S(SC1=NC2=CC=CC=C2S1)C3=NC4=C(S3)C=CC=C4", "CC1=CC(=O)C=CC1=O", "OC1=C(Cl)C=C(C=C1[N+]([O-])=O)[N+]([O-])=O", "[O-][N+](=O)C1=CNC(=N)S1", "NC1=CC2=C(C=C1)C(=O)C3=C(C=CC=C3)C2=O", "OC(=O)C1=C(C=CC=C1)C2=C3C=CC(=O)C(=C3OC4=C2C=CC(=C4Br)O)Br", "CN(C)C1=C(Cl)C(=O)C2=C(C=CC=C2)C1=O", "CC1=C(C2=C(C=C1)C(=O)C3=CC=CC=C3C2=O)[N+]([O-])=O", "CC(=NO)C(C)=NO"] self.smiList2 = ['OCCC', 'CCC', 'C=CC', 'OC=CC', 'CC(O)C', 'C=C(O)C', 'OCCCC', 'CC(O)CC', 'C=CCC', 'CC=CC', 'OC=CCC', 'CC=C(O)C', 'OCC=CC', 'C=C(O)CC', 'C=CC(O)C', 'C=CCCO', ] self.list2Acts = [1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1] self.list2Obls = [(0, 1, 2), (1, 3), (1, 4, 5), (1, 6, 7), (0, 8), (0, 6, 9), (0, 1, 2, 3, 10), (0, 1, 2, 8, 11), (1, 3, 4, 5, 12), (1, 4, 5, 13), (1, 3, 6, 7, 14), (0, 1, 6, 7, 9, 15)] ffile = os.path.join(RDConfig.RDDataDir, 'FunctionalGroups.txt') self.catParams = FragmentCatalog.FragCatParams(1, 6, ffile) self.fragCat = FragmentCatalog.FragCatalog(self.catParams) self.fgen = FragmentCatalog.FragCatGenerator() def _fillCat(self, smilList): for smi in self.smiList2: mol = Chem.MolFromSmiles(smi) self.fgen.AddFragsFromMol(mol, self.fragCat) def _testBits(self, fragCat): fpgen = FragmentCatalog.FragFPGenerator() obits = [3, 2, 3, 3, 2, 3, 5, 5, 5, 4, 5, 6] obls = self.list2Obls suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList2), ',', 0, -1, 0) i = 0 for mol in suppl: fp = fpgen.GetFPForMol(mol, fragCat) if i < len(obits): smi = Chem.MolToSmiles(mol) assert fp.GetNumOnBits() == obits[i], '%s: %s' % (smi, str(fp.GetOnBits())) obl = fp.GetOnBits() if i < len(obls): assert tuple(obl) == obls[i], '%s: %s' % (smi, obl) i += 1 def test1CatGen(self): self._fillCat(self.smiList2) assert self.fragCat.GetNumEntries() == 21 assert self.fragCat.GetFPLength() == 21 self._testBits(self.fragCat) def test2CatStringPickle(self): self._fillCat(self.smiList2) # test non-binary pickle: cat2 = cPickle.loads(cPickle.dumps(self.fragCat)) assert cat2.GetNumEntries() == 21 assert cat2.GetFPLength() == 21 self._testBits(cat2) # test binary pickle: cat2 = cPickle.loads(cPickle.dumps(self.fragCat, 1)) assert cat2.GetNumEntries() == 21 assert cat2.GetFPLength() == 21 self._testBits(cat2) def test3CatFilePickle(self): with open(os.path.join(RDConfig.RDCodeDir, 'Chem', 'test_data', 'simple_catalog.pkl'), 'r') as pklTFile: buf = pklTFile.read().replace('\r\n', '\n').encode('utf-8') pklTFile.close() with io.BytesIO(buf) as pklFile: cat = cPickle.load(pklFile, encoding='bytes') assert cat.GetNumEntries() == 21 assert cat.GetFPLength() == 21 self._testBits(cat) def test4CatGuts(self): self._fillCat(self.smiList2) assert self.fragCat.GetNumEntries() == 21 assert self.fragCat.GetFPLength() == 21 # # FIX: (Issue 162) # bits like 11 and 15 are questionable here because the underlying # fragments are symmetrical, so they can generate one of two # text representations (i.e. there is nothing to distinguish # between 'CC<-O>CC' and 'CCC<-O>C'). # This ought to eventually be cleaned up. descrs = [(0, 'C<-O>C', 1, (34, )), (1, 'CC', 1, ()), (2, 'C<-O>CC', 2, (34, )), (3, 'CCC', 2, ()), (4, 'C=C', 1, ()), (5, 'C=CC', 2, ()), (6, 'C<-O>=C', 1, (34, )), (7, 'C<-O>=CC', 2, (34, )), (8, 'CC<-O>C', 2, (34, )), (9, 'C=C<-O>C', 2, (34, )), (10, 'C<-O>CCC', 3, (34, )), (11, 'CC<-O>CC', 3, (34, )), (12, 'C=CCC', 3, ()), (13, 'CC=CC', 3, ()), (14, 'C<-O>=CCC', 3, (34, )), (15, 'CC=C<-O>C', 3, (34, )), (16, 'C=CC<-O>', 2, (34, )), ] for i in range(len(descrs)): id, d, order, ids = descrs[i] descr = self.fragCat.GetBitDescription(id) assert descr == d, '%d: %s != %s' % (id, descr, d) assert self.fragCat.GetBitOrder(id) == order assert tuple(self.fragCat.GetBitFuncGroupIds(id)) == \ ids,'%d: %s != %s'%(id, str(self.fragCat.GetBitFuncGroupIds(id)), str(ids)) def _test5MoreComplex(self): lastIdx = 0 ranges = {} suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList), ',', 0, -1, 0) i = 0 for mol in suppl: nEnt = self.fgen.AddFragsFromMol(mol, self.fragCat) ranges[i] = range(lastIdx, lastIdx + nEnt) lastIdx += nEnt i += 1 # now make sure that those bits are contained in the signatures: fpgen = FragmentCatalog.FragFPGenerator() i = 0 for mol in suppl: fp = fpgen.GetFPForMol(mol, self.fragCat) for bit in ranges[i]: assert fp[bit], '%s: %s' % (Chem.MolToSmiles(mol), str(bit)) i += 1 def test6Builder(self): suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList2), ',', 0, -1, 0) cat = BuildFragmentCatalog.BuildCatalog(suppl, minPath=1, reportFreq=20) assert cat.GetNumEntries() == 21 assert cat.GetFPLength() == 21 self._testBits(cat) def test7ScoreMolecules(self): suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList2), ',', 0, -1, 0) cat = BuildFragmentCatalog.BuildCatalog(suppl, minPath=1, reportFreq=20) assert cat.GetNumEntries() == 21 assert cat.GetFPLength() == 21 scores, obls = BuildFragmentCatalog.ScoreMolecules(suppl, cat, acts=self.list2Acts, reportFreq=20) for i in range(len(self.list2Obls)): assert tuple(obls[i]) == self.list2Obls[i], '%d: %s != %s' % (i, str(obls[i]), str(self.list2Obls[i])) scores2 = BuildFragmentCatalog.ScoreFromLists(obls, suppl, cat, acts=self.list2Acts, reportFreq=20) for i in range(len(scores)): assert (scores[i] == scores2[i]).all(), '%d: %s != %s' % (i, str(scores[i]), str(scores2[i])) def test8MolRanks(self): suppl = Chem.SmilesMolSupplierFromText('\n'.join(self.smiList2), ',', 0, -1, 0) cat = BuildFragmentCatalog.BuildCatalog(suppl, minPath=1, reportFreq=20) assert cat.GetNumEntries() == 21 assert cat.GetFPLength() == 21 # new InfoGain ranking: bitInfo, fps = BuildFragmentCatalog.CalcGains(suppl, cat, topN=10, acts=self.list2Acts, reportFreq=20, biasList=(1, )) entry = bitInfo[0] assert int(entry[0]) == 0 assert cat.GetBitDescription(int(entry[0])) == 'C<-O>C' assert feq(entry[1], 0.4669) entry = bitInfo[1] assert int(entry[0]) in (2, 6) txt = cat.GetBitDescription(int(entry[0])) self.assertTrue(txt in ('C<-O>CC', 'C<-O>=C'), txt) assert feq(entry[1], 0.1611) entry = bitInfo[6] assert int(entry[0]) == 16 assert cat.GetBitDescription(int(entry[0])) == 'C=CC<-O>' assert feq(entry[1], 0.0560) # standard InfoGain ranking: bitInfo, fps = BuildFragmentCatalog.CalcGains(suppl, cat, topN=10, acts=self.list2Acts, reportFreq=20) entry = bitInfo[0] assert int(entry[0]) == 0 assert cat.GetBitDescription(int(entry[0])) == 'C<-O>C' assert feq(entry[1], 0.4669) entry = bitInfo[1] assert int(entry[0]) == 5 assert cat.GetBitDescription(int(entry[0])) == 'C=CC' assert feq(entry[1], 0.2057) def test9Issue116(self): smiList = ['Cc1ccccc1'] suppl = Chem.SmilesMolSupplierFromText('\n'.join(smiList), ',', 0, -1, 0) cat = BuildFragmentCatalog.BuildCatalog(suppl, minPath=2, maxPath=2) assert cat.GetFPLength() == 2 assert cat.GetBitDescription(0) == 'ccC' fpgen = FragmentCatalog.FragFPGenerator() mol = Chem.MolFromSmiles('Cc1ccccc1') fp = fpgen.GetFPForMol(mol, cat) assert fp[0] assert fp[1] mol = Chem.MolFromSmiles('c1ccccc1-c1ccccc1') fp = fpgen.GetFPForMol(mol, cat) assert not fp[0] assert fp[1] if __name__ == '__main__': unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/UnitTestCatalog.py", "copies": "1", "size": "9354", "license": "bsd-3-clause", "hash": -8283884744181282000, "line_mean": 36.5662650602, "line_max": 99, "alpha_frac": 0.5440453282, "autogenerated": false, "ratio": 2.8285455095252496, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8840979317007702, "avg_score": 0.006322304143509522, "num_lines": 249 }
import random import unittest from rdkit.six import StringIO from rdkit.DataStructs.TopNContainer import TopNContainer, _exampleCode from rdkit.TestRunner import redirect_stdout class TestCase(unittest.TestCase): def test1(self): # simple test with a known answer cont = TopNContainer(4) for foo in range(10): cont.Insert(foo, str(foo)) assert cont.GetPts() == list(range(6, 10)) assert cont.GetExtras() == [str(x) for x in range(6, 10)] def test2(self): # larger scale random test cont = TopNContainer(50) for _ in range(1000): cont.Insert(random.random()) vs = cont.GetPts() last = vs.pop(0) while vs: assert vs[0] >= last last = vs.pop(0) def test3(self): # random test with extras cont = TopNContainer(10) for _ in range(100): v = random.random() cont.Insert(v, v + 1) vs = cont.GetExtras() last = vs.pop(0) while vs: assert vs[0] >= last last = vs.pop(0) def test4(self): # random test with extras and getitem cont = TopNContainer(10) for i in range(100): v = random.random() cont.Insert(v, v + 1) lastV, lastE = cont[0] for i in range(1, len(cont)): v, e = cont[i] assert v >= lastV assert e >= lastE lastV, lastE = v, e def test5(self): # random test with extras and getitem, include reverse cont = TopNContainer(10) for i in range(100): v = random.random() cont.Insert(v, v + 1) cont.reverse() lastV, lastE = cont[0] for i in range(1, len(cont)): v, e = cont[i] assert v <= lastV assert e <= lastE lastV, lastE = v, e def test_keepAll(self): # simple test with a known answer where we keep all cont = TopNContainer(-1) for i in range(10): cont.Insert(9 - i, str(9 - i)) self.assertEqual(len(cont), i + 1) assert cont.GetPts() == list(range(10)) assert cont.GetExtras() == [str(x) for x in range(10)] def test_exampleCode(self): # We make sure that the example code runs f = StringIO() with redirect_stdout(f): _exampleCode() s = f.getvalue() self.assertIn('[58, 75, 78, 84]', s) if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/DataStructs/UnitTestTopNContainer.py", "copies": "4", "size": "2548", "license": "bsd-3-clause", "hash": -4922052235652594000, "line_mean": 24.7373737374, "line_max": 71, "alpha_frac": 0.6087127159, "autogenerated": false, "ratio": 3.2253164556962024, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5834029171596202, "avg_score": null, "num_lines": null }
import unittest import random from rdkit.DataStructs.TopNContainer import TopNContainer class TestCase(unittest.TestCase): def test1(self): """ simple test with a known answer """ cont = TopNContainer(4) for foo in range(10): cont.Insert(foo,str(foo)) assert cont.GetPts()==range(6,10) assert cont.GetExtras()==[str(x) for x in range(6,10)] def test2(self): """ larger scale random test """ cont = TopNContainer(50) for i in range(1000): cont.Insert(random.random()) vs = cont.GetPts() last = vs.pop(0) while vs: assert vs[0]>=last last = vs.pop(0) def test3(self): """ random test with extras""" cont = TopNContainer(10) for i in range(100): v = random.random() cont.Insert(v,v+1) vs = cont.GetExtras() last = vs.pop(0) while vs: assert vs[0]>=last last = vs.pop(0) def test4(self): """ random test with extras and getitem""" cont = TopNContainer(10) for i in range(100): v = random.random() cont.Insert(v,v+1) lastV,lastE = cont[0] for i in range(1,len(cont)): v,e = cont[i] assert v>=lastV assert e>=lastE lastV,lastE = v,e def test5(self): """ random test with extras and getitem, include reverse""" cont = TopNContainer(10) for i in range(100): v = random.random() cont.Insert(v,v+1) cont.reverse() lastV,lastE = cont[0] for i in range(1,len(cont)): v,e = cont[i] assert v<=lastV assert e<=lastE lastV,lastE = v,e if __name__ == '__main__': unittest.main()
{ "repo_name": "soerendip42/rdkit", "path": "rdkit/DataStructs/UnitTestTopNContainer.py", "copies": "5", "size": "1888", "license": "bsd-3-clause", "hash": -8907564040054778000, "line_mean": 25.5915492958, "line_max": 63, "alpha_frac": 0.6054025424, "autogenerated": false, "ratio": 3.1362126245847177, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.032759946233565165, "num_lines": 71 }
"""basic unit testing code for the Bond wrapper """ import unittest from rdkit import Chem class TestCase(unittest.TestCase): def setUp(self): #print '\n%s: '%self.shortDescription(), self.m = Chem.MolFromSmiles('CCCC1=CC=C1') def test1Get(self): " testing GetBond " ok = 1 try: b = self.m.GetBondBetweenAtoms(0,1) except Exception: ok = 0 assert ok,'GetBond failed' def test2Setters(self): " testing setting bond props " b = self.m.GetBondBetweenAtoms(0,1) assert b.GetBondType()==Chem.BondType.SINGLE b.SetBondDir(Chem.BondDir.BEGINWEDGE) assert self.m.GetBondBetweenAtoms(0,1).GetBondDir()==Chem.BondDir.BEGINWEDGE b = self.m.GetBondBetweenAtoms(0,1) def test3Props(self): " testing bond props " b = self.m.GetBondBetweenAtoms(0,1) assert b.GetBondType()==Chem.BondType.SINGLE assert b.GetBeginAtom().GetIdx()==self.m.GetAtomWithIdx(0).GetIdx() assert b.GetBeginAtomIdx()==0 assert b.GetEndAtom().GetIdx()==self.m.GetAtomWithIdx(1).GetIdx() assert b.GetEndAtomIdx()==1 def test4Props2(self): " testing more bond props " b = self.m.GetBondBetweenAtoms(3,4) assert b.GetBondType()==Chem.BondType.DOUBLE b2 = self.m.GetBondBetweenAtoms(1,2) assert b2.GetBondType()==Chem.BondType.SINGLE assert b.GetIsConjugated() assert not b2.GetIsConjugated() if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/UnitTestChemBond.py", "copies": "1", "size": "1727", "license": "bsd-3-clause", "hash": 3068124647451514000, "line_mean": 25.984375, "line_max": 80, "alpha_frac": 0.6763173133, "autogenerated": false, "ratio": 2.84983498349835, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.402615229679835, "avg_score": null, "num_lines": null }
""" Tools for doing PubMed searches and processing the results NOTE: much of the example code in the documentation here uses XML files from the test_data directory in order to avoid having to call out to PubMed itself. Actual calls to the functions would not include the _conn_ argument. """ from rdkit import RDConfig import QueryParams,Records import urllib,urllib2 from xml.etree import ElementTree def openURL(url,args): proxy_support = urllib2.ProxyHandler({}) opener = urllib2.build_opener(proxy_support) conn = urllib2.urlopen(url,args) return conn def GetNumHits(query,url=QueryParams.searchBase): """ returns a tuple of pubmed ids (strings) for the query provided To do a search, we need a query object: >>> query = QueryParams.details() set up the search parameters: >>> query['term'] = 'penzotti je AND grootenhuis pd' >>> query['field'] = 'auth' now get the search ids: >>> counts = GetNumHits(query) >>> counts 2 alternately, we can search using field specifiers: >>> query = QueryParams.details() >>> query['term'] = 'penzotti je[au] AND hydrogen bonding[mh]' >>> counts = GetNumHits(query) >>> counts 3 """ query['rettype']='count' conn = openURL(url,urllib.urlencode(query)) pubmed = ElementTree.parse(conn) countText = pubmed.findtext('Count') if countText: res = int(countText) else: res = 0 return res def GetSearchIds(query,url=QueryParams.searchBase): """ returns a tuple of pubmed ids (strings) for the query provided To do a search, we need a query object: >>> query = QueryParams.details() set up the search parameters: >>> query['term'] = 'penzotti je AND grootenhuis pd' >>> query['field'] = 'auth' now get the search ids: >>> ids = GetSearchIds(query) >>> len(ids) 2 >>> ids[0] '11960484' >>> ids[1] '10893315' """ conn = openURL(url,urllib.urlencode(query)) pubmed = ElementTree.parse(conn) res = [id.text for id in pubmed.getiterator('Id')] return tuple(res) def GetSummaries(ids,query=None,url=QueryParams.summaryBase,conn=None): """ gets a set of document summary records for the ids provided >>> ids = ['11960484'] >>> summs = GetSummaries(ids,conn=open(os.path.join(testDataDir,'summary.xml'),'r')) >>> len(summs) 1 >>> rec = summs[0] >>> isinstance(rec,Records.SummaryRecord) 1 >>> rec.PubMedId '11960484' >>> rec.Authors 'Penzotti JE, Lamb ML, Evensen E, Grootenhuis PD' >>> rec.Title 'A computational ensemble pharmacophore model for identifying substrates of P-glycoprotein.' >>> rec.Source 'J Med Chem' >>> rec.Volume '45' >>> rec.Pages '1737-40' >>> rec.HasAbstract '1' """ if not conn: try: iter(ids) except TypeError: ids = [ids,] if not query: query = QueryParams.details() ids = map(str,ids) query['id'] = ','.join(ids) conn = openURL(url,urllib.urlencode(query)) pubmed = ElementTree.parse(conn) res = [] for summary in pubmed.getiterator('DocSum'): rec = Records.SummaryRecord(summary) if rec.PubMedId in ids: res.append(rec) ids.remove(rec.PubMedId) return tuple(res) def GetRecords(ids,query=None,url=QueryParams.fetchBase,conn=None): """ gets a set of document summary records for the ids provided >>> ids = ['11960484'] >>> recs = GetRecords(ids,conn=open(os.path.join(testDataDir,'records.xml'),'r')) >>> len(recs) 1 >>> rec = recs[0] >>> rec.PubMedId '11960484' >>> rec.Authors u'Penzotti JE, Lamb ML, Evensen E, Grootenhuis PD' >>> rec.Title u'A computational ensemble pharmacophore model for identifying substrates of P-glycoprotein.' >>> rec.Source u'J Med Chem' >>> rec.Volume '45' >>> rec.Pages '1737-40' >>> rec.PubYear '2002' >>> rec.Abstract[:10] u'P-glycopro' We've also got access to keywords: >>> str(rec.keywords[0]) 'Combinatorial Chemistry Techniques' >>> str(rec.keywords[3]) 'Indinavir / chemistry' and chemicals: >>> rec.chemicals[0] 'P-Glycoprotein' >>> rec.chemicals[2] 'Nicardipine <55985-32-5>' """ if not conn: try: iter(ids) except TypeError: ids = [ids,] if not query: query = QueryParams.details() query['id'] = ','.join(map(str,ids)) conn = openURL(url,urllib.urlencode(query)) pubmed = ElementTree.parse(conn) res = [] for article in pubmed.getiterator('PubmedArticle'): rec = Records.JournalArticleRecord(article) if rec.PubMedId in ids: res.append(rec) return tuple(res) def CheckForLinks(ids,query=None,url=QueryParams.linkBase,conn=None): if not conn: try: iter(ids) except TypeError: ids = [ids,] if not query: query = QueryParams.details() query['id'] = ','.join(map(str,ids)) conn = openURL(url,urllib.urlencode(query)) query['cmd'] = 'ncheck' pubmed = ElementTree.parse(conn) checklist = pubmed.find('LinkSet/IdCheckList') recs = [Records.LinkRecord(x) for x in checklist.getiterator('Id')] res = {} for rec in recs: id = rec.PubMedId res[id] = rec.HasNeighbor return res def GetLinks(ids,query=None,url=QueryParams.linkBase,conn=None): if not conn: try: iter(ids) except TypeError: ids = [ids,] if not query: query = QueryParams.details() query['id'] = ','.join(map(str,ids)) conn = openURL(url,urllib.urlencode(query)) query['cmd'] = 'neighbor' pubmed = ElementTree.parse(conn) linkset = pubmed.find('LinkSet/LinkSetDb') scores = [] scoreNorm = 1.0 for link in linkset.getiterator('Link'): id = link.findtext('Id') score = float(link.findtext('Score')) scores.append([id,score]) # we'll normalize scores by the score for the first of the query ids: if id == ids[0]: scoreNorm = score for i in range(len(scores)): id,score = scores[i] scores[i] = id,score/scoreNorm return tuple(scores) #------------------------------------ # # doctest boilerplate # def _test(): import doctest,sys return doctest.testmod(sys.modules["__main__"]) if __name__ == '__main__': import sys,os.path testDataDir = os.path.join(RDConfig.RDCodeDir,'Dbase','Pubmed','test_data') failed,tried = _test() sys.exit(failed) #query = QueryParams.details() #query['term']='landrum ga' #query['field']='auth' #ids = GetSearchIds(query) #print ids #ids = ids[:2] ids = ['11666868','11169640'] if 0: summs = GetSummaries(ids,conn=open('summary.xml','r')) print 'summs:',summs for summary in summs: print summary.Authors print '\t',summary.Title print '\t',summary.Source, print summary.Volume, print summary.Pages, print summary.PubDate if 0: ids = ['11666868'] res = GetRecords(ids,conn=open('records.xml','r')) for record in res: print record.Authors print '\t',record.Title print '\t',record.Journal, print record.Volume, print record.Pages, print record.PubYear print if 0: ids = ['11666868','11169640'] res = CheckForLinks(ids,conn=open('haslinks.xml','r')) print res if 0: ids = ['11666868'] res = GetLinks(ids,conn=open('links.xml','r')) #res = GetLinks(ids) for id,score in res[:10]: print id,score
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Dbase/Pubmed/Searches.py", "copies": "2", "size": "7576", "license": "bsd-3-clause", "hash": -8097189635520018000, "line_mean": 24.3377926421, "line_max": 95, "alpha_frac": 0.6446673706, "autogenerated": false, "ratio": 3.1765199161425577, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.965741477935799, "avg_score": 0.032754501476913604, "num_lines": 299 }
try: from reportlab import platypus except ImportError: import sys sys.stderr.write('ReportLab module could not be imported. Db->PDF functionality not available') GetReportlabTable = None QuickReport = None else: from rdkit import Chem try: from pyRDkit.utils import chemdraw except ImportError: hasCDX=0 else: hasCDX=1 from rdkit.utils import cactvs from rdkit.Chem import rdDepictor from rdkit.Chem.Draw import DrawUtils from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbInfo from rdkit.Reports.PDFReport import PDFReport,ReportUtils import os,tempfile,sys def GetReportlabTable(self,*args,**kwargs): """ this becomes a method of DbConnect """ dbRes = self.GetData(*args,**kwargs) rawD = [dbRes.GetColumnNames()] colTypes = dbRes.GetColumnTypes() binCols = [] for i in range(len(colTypes)): if colTypes[i] in DbInfo.sqlBinTypes or colTypes[i]=='binary': binCols.append(i) nRows = 0 for entry in dbRes: nRows += 1 for col in binCols: entry = list(entry) entry[col] = 'N/A' rawD.append(entry) #if nRows >10: break res = platypus.Table(rawD) return res from reportlab.lib.units import inch class CDXImageTransformer(object): def __init__(self,smiCol,width=1,verbose=1,tempHandler=None): self.smiCol = smiCol if tempHandler is None: tempHandler = ReportUtils.TempFileHandler() self.tempHandler = tempHandler self.width = width*inch self.verbose=verbose def __call__(self,arg): res = list(arg) if self.verbose: print 'Render:',res[0] if hasCDX: smi = res[self.smiCol] tmpName = self.tempHandler.get('.jpg') try: img = chemdraw.SmilesToPilImage(smi) w,h = img.size aspect = float(h)/w img.save(tmpName) img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect*self.width res[self.smiCol] = img except: import traceback traceback.print_exc() res[self.smiCol] = 'Failed' return res class CactvsImageTransformer(object): def __init__(self,smiCol,width=1.,verbose=1,tempHandler=None): self.smiCol = smiCol if tempHandler is None: tempHandler = ReportUtils.TempFileHandler() self.tempHandler = tempHandler self.width = width*inch self.verbose=verbose def __call__(self,arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n'%(self.smiCol,str(res[0]))) smi = res[self.smiCol] tmpName = self.tempHandler.get('.gif') aspect = 1 width = 300 height = aspect*width ok = cactvs.SmilesToGif(smi,tmpName,(width,height)) if ok: try: img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect*self.width except: ok = 0 if ok: res[self.smiCol] = img else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res from rdkit.sping.ReportLab.pidReportLab import RLCanvas as Canvas from rdkit.Chem.Draw.MolDrawing import MolDrawing class ReportLabImageTransformer(object): def __init__(self,smiCol,width=1.,verbose=1,tempHandler=None): self.smiCol = smiCol self.width = width*inch self.verbose=verbose def __call__(self,arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n'%(self.smiCol,str(res[0]))) smi = res[self.smiCol] aspect = 1 width = self.width height = aspect*width try: mol = Chem.MolFromSmiles(smi) Chem.Kekulize(mol) canv = Canvas((width,height)) drawing = MolDrawing() drawing.atomLabelMinFontSize=3 drawing.minLabelPadding=(.5,.5) drawing.bondLineWidth=0.5 if not mol.GetNumConformers(): rdDepictor.Compute2DCoords(mol) drawing.AddMol(mol,canvas=canv) ok = True except: if self.verbose: import traceback traceback.print_exc() ok = False if ok: res[self.smiCol] = canv.drawing else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res class RDImageTransformer(object): def __init__(self,smiCol,width=1.,verbose=1,tempHandler=None): self.smiCol = smiCol if tempHandler is None: tempHandler = ReportUtils.TempFileHandler() self.tempHandler = tempHandler self.width = width*inch self.verbose=verbose def __call__(self,arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n'%(self.smiCol,str(res[0]))) smi = res[self.smiCol] tmpName = self.tempHandler.get('.jpg') aspect = 1 width = 300 height = aspect*width ok = DrawUtils.SmilesToJpeg(smi,tmpName,size=(width,height)) if ok: try: img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect*self.width except: ok = 0 if ok: res[self.smiCol] = img else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res def QuickReport(conn,fileName,*args,**kwargs): from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch styles = getSampleStyleSheet() title = 'Db Report' if kwargs.has_key('title'): title = kwargs['title'] del kwargs['title'] names = [x.upper() for x in conn.GetColumnNames()] try: smiCol = names.index('SMILES') except ValueError: try: smiCol = names.index('SMI') except ValueError: smiCol = -1 if smiCol >-1: if hasCDX: tform = CDXImageTransformer(smiCol) elif 1: tform = ReportLabImageTransformer(smiCol) else: tform = CactvsImageTransformer(smiCol) else: tform = None kwargs['transform'] = tform tbl = conn.GetReportlabTable(*args,**kwargs) tbl.setStyle(platypus.TableStyle([('GRID',(0,0),(-1,-1),1,colors.black), ('FONT',(0,0),(-1,-1),'Times-Roman',8), ])) if smiCol >-1 and tform: tbl._argW[smiCol] = tform.width*1.2 elements = [tbl] reportTemplate = PDFReport() reportTemplate.pageHeader = title doc = platypus.SimpleDocTemplate(fileName) doc.build(elements,onFirstPage=reportTemplate.onPage, onLaterPages=reportTemplate.onPage) DbConnect.GetReportlabTable = GetReportlabTable if __name__=='__main__': import sys dbName = sys.argv[1] tblName = sys.argv[2] fName = 'report.pdf' conn = DbConnect(dbName,tblName) QuickReport(conn,fName,where="where mol_id in ('1','100','104','107')")
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Dbase/DbReport.py", "copies": "1", "size": "7416", "license": "bsd-3-clause", "hash": 6540975674846323000, "line_mean": 29.024291498, "line_max": 98, "alpha_frac": 0.6115156419, "autogenerated": false, "ratio": 3.4719101123595504, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9394748031190312, "avg_score": 0.03773554461384775, "num_lines": 247 }
""" Unit Test code for Fragment Descriptors """ import unittest from rdkit import Chem from rdkit.Chem import Fragments class TestCase(unittest.TestCase): def setUp(self) : pass def _runTest(self,data,fn): for smi,tgtVal in data: mol = Chem.MolFromSmiles(smi) assert mol,"Smiles parsing failed for %s"%(smi) count = fn(mol) assert count==tgtVal,"bad value (%d != %d) for smiles %s"%(count,tgtVal,smi) def test1(self): data = [('C=O',1), ('O=CC=O',2), ('O=CC(=O)O',2), ('O=C(O)C(=O)O',2), ] self._runTest(data,Fragments.fr_C_O) def test2(self): data = [('C=O',1), ('O=CC=O',2), ('O=CC(=O)O',1), ('O=C(O)C(=O)O',0), ] self._runTest(data,Fragments.fr_C_O_noCOO) def test3(self): data = [('[O-][N+](C1=C([N+]([O-])=O)C=C([N+]([O-])=O)C=C1)=O',3), ('[O-][N+](C1=CC=CC=C1)=O', 1), ('[N+]([O-])(=O)C1OC(=CC=1)/C=N/NC(N)=O', 0), ('O=C(O)C(=O)O',0), ] self._runTest(data,Fragments.fr_nitro_arom) def test4(self): data = [('[O-][N+](C1=C([N+]([O-])=O)C=C([N+]([O-])=O)C=C1)=O',1), ('[O-][N+](C1=CC=CC=C1)=O', 1), ('[N+]([O-])(=O)C1OC(=CC=1)/C=N/NC(N)=O', 0), ('O=C(O)C(=O)O',0), ] self._runTest(data,Fragments.fr_nitro_arom_nonortho) def test5(self): data = [('C1(N=[N+]=[N-])=C(C(=C(C(=C1F)F)F)F)F',1), ] self._runTest(data,Fragments.fr_azide) def test6(self): data = [('C1C=CNC=C1',1), ('C1=CCNC=C1',1), ('C1=CCN=CC1',1), ('C1=CC=NCC1',1), ('C1C=CC(=CC=1[N+]([O-])=O)C2C(=C(NC(=C2C(OC)=O)C)C)C(OCCNCC3=CC=CC=C3)=O',1), ('O=C(O)C(=O)O',0), ] self._runTest(data,Fragments.fr_dihydropyridine) def test7(self): data = [('OC1=C(C(O)=O)C=CC=C1',0), ('OC1=CC=CC=C1',1), ('OC1=C(O)C=CC=C1',2), ('O=C(O)C1=CC(O)=CC=C1',1), ('OC1=C(O)C(C(O)=O)=CC=C1',1), ('OC1=C(C(N)=O)C=CC=C1',0), ('OC1=C(CO)C=CC=C1',0), ('OC1=C(C(OC)=O)C=CC=C1',1), ('C1=CC=NCC1',0), ('C1C=CC(=CC=1[N+]([O-])=O)C2C(=C(NC(=C2C(OC)=O)C)C)C(OCCNCC3=CC=CC=C3)=O',0), ('O=C(O)C(=O)O',0), ] self._runTest(data,Fragments.fr_phenol_noOrthoHbond) def test8(self): data = [('OC1=C(C(O)=O)C=CC=C1',0), ('CC(C)(O)C',0), ('CC(O)C',1), ('C=C(O)C',1), # includes enols ('OC1=C(O)C=CC=C1',0), ('OC1=C(CO)C=CC=C1',1), ('C1C=CC(=CC=1[N+]([O-])=O)C2C(=C(NC(=C2C(OC)=O)C)C)C(OCCNCC3=CC=CC=C3)=O',0) ] self._runTest(data,Fragments.fr_Al_OH_noTert) def test9(self): data = [('OC1=C(C(O)=O)C=CC=C1',0), ('C12=CC=CC=C1NCCN=C2',1), ('C1=C(C=C2C(=C1)NC(CN=C2C3=C(C=CC=C3)Cl)=O)[N+]([O-])=O',1), # clonazepam ('C12=C(C(=NCC(N1C)=O)C3=CC=CC=C3)C=C(C=C2)Cl',1), # valium ('CCC1=CC2C(=NCC(=O)N(C)C=2S1)C3=CC=CC=C3Cl',0), # clotiazepam has a 5-mb ring ('CN(C)CCN1C(=O)C2=CC=CC=C2NC3C=C(Cl)C=CC1=3',0), #clobenzepam has a third fused ring ('C1C=CC(=CC=1[N+]([O-])=O)C2C(=C(NC(=C2C(OC)=O)C)C)C(OCCNCC3=CC=CC=C3)=O',0) ] self._runTest(data,Fragments.fr_benzodiazepine) def test10(self): data = [('OC1=C(C(O)=O)C=CC=C1',1), ('c1ccccc1Oc2ccccc2',2), # diphenyl ether has 2 sites ('COC1=CC=CC=C1',1), ('CN(C)C2=CC=CC=C2',1), ('O=C(C4=CC=CC=C4)C3=CC=CC=C3',0), ('COC1=CC=C(C)C(OC)=C1C',0), ('CN(C)C1=CC=CC=C1OC',2), ('O=C(C2=CC=CC=C2)CC1=CC=CC=C1',0), ('O=C(NC2=CC=CC=C2)CN(C)C1=CC=CC=C1',2), ('O=C(N(C)C2=CC=CC=C2)CC1=CC=CC=C1',1), # methylated amide is included ('C12=CC=CC=C1OCCC2',1), ('C12=CC=CC=C1OC=C2',1), # benzofuran ('C12=CC=CC=C1NC=N2',2), # benzimidazole hydroxylated at 5 position ('CC1=CC=C(C=CO2)C2=C1',0) ] self._runTest(data,Fragments.fr_para_hydroxylation) def test11(self): data = [('C1C(C=C2[C@](C1)([C@]3([C@@](CC2)([C@]4([C@](CC3)([C@@H](CC4)O)C)[H])[H])[H])C)=O',1), # testosterone 6beta hydroxylation includedbut not dienone ('CCC=CCCC',2), ('C=CC',1), ('C=CCO',0) ] self._runTest(data,Fragments.fr_allylic_oxid) def test12(self): data = [('c1ccccc1C',1), ('c1ccccc1CC',1), ('c1(C)cccc(C)c1CC',2), ('c1(N)cccc(O)c1CC',0), ('c1cccc(C)c1CC',2), ('c1ccccc1CN',0), ('c1ccccc1CCN',0), ('c1(C)ccccc1CCN',1) ] self._runTest(data,Fragments.fr_aryl_methyl) def test13(self): data = [('CNC1(CCCCC1=O)C2(=CC=CC=C2Cl)',1), # ketamine ('C1=C(C(=C(C=C1)C)NC(CN(CC)CC)=O)C',1), # lidocaine ('c1(C)ccccc1CCN',0) ] self._runTest(data,Fragments.fr_Ndealkylation1) def test14(self): data = [('C12(=C(N=CC=C1[C@@H](O)C3(N4CC(C(C3)CC4)([H])C=C)[H])C=CC(=C2)OC)',0), # quinine ('N12CCC(CC2)CC1',0), # bridged N ('N1(CCC)CCCCC1',1), ('CCC1(CCCCN(C)C1)C2=CC=CC(O)=C2',1), # meptazinol ('C1(=C2C3=C(C=C1)C[C@@H]4[C@]5([C@@]3([C@H]([C@H](CC5)O)O2)CCN4CC6CCC6)O)O',1), # nalbuphine ('CC1N=C2CCCCN2C(=O)C=1CCN3CCC(CC3)C4=NOC5C=C(F)C=CC4=5',1), # risperidone ('N1CCOCC1',0), # morpholino group ('n1ccccc1',0) ] self._runTest(data,Fragments.fr_Ndealkylation2) def test15(self): data = [('C(COC(NC(C)C)=O)(COC(N)=O)(CCC)C',1), # carisoprodol ('CN(CC3=CSC(C(C)C)=N3)C(N[C@@H]([C@H](C)C)C(N[C@@H](CC4=CC=CC=C4)C[C@H](O)[C@H](CC2=CC=CC=C2)NC(OCC1=CN=CS1)=O)=O)=O',1), # ritonavir ('c1(C)ccccc1CCN',0) ] self._runTest(data,Fragments.fr_alkyl_carbamate) def test16(self): data = [('C1(CCC(O1)=O)(C)CC/C=C\CC',1), ('CN(CC3=CSC(C(C)C)=N3)C(N[C@@H]([C@H](C)C)C(N[C@@H](CC4=CC=CC=C4)C[C@H](O)[C@H](CC2=CC=CC=C2)NC(OCC1=CN=CS1)=O)=O)=O',0), # ritonavir ('c1(C)ccccc1CCN',0) ] self._runTest(data,Fragments.fr_lactone) def test17(self): data = [('O=C(C=CC1=CC=CC=C1)C=CC2=CC=CC=C2',0), # a,b-unsat. dienone ('c1ccccc1-C(=O)-c2ccccc2',0), ('c1ccccc1-C(=O)-CCO',1), ('CC(=O)NCCC',0) ] self._runTest(data,Fragments.fr_ketone_Topliss) def test18(self): data = [('C1=CC(=CC=C1C(N[C@@H](CCC(O)=O)C(O)=O)=O)N(CC2=NC3C(=NC(=NC=3N=C2)N)N)C',2), # methotrexate ('S(NC1=NC=CC=N1)(=O)(=O)C2=CC=C(C=C2)N',1), # sulfadiazine ('S(NC1=NC=CC=N1)(=O)(=O)C2=CC=C(C=C2)',0), ('c1ccccc1-C(=O)-CCO',0), ('NNC(=O)C1C2CCCCC=2N=C3C=CC=CC=13',1), ('NC(=N)C1C2CCCCC=2N=C3C=CC=CC=13',1), ('NNC1C2CCCCC=2N=C3C=CC=CC=13',1), ('NC1C2CCCCC=2N=C3C=CC=CC=13',1) # tacrine ] self._runTest(data,Fragments.fr_ArN) def test19(self): data = [('CC(C)(C)NCC(O)C1=CC(O)=CC(O)=C1',1), # terbulatine ('OCCN1CCN(CC/C=C2\C3=CC=CC=C3SC4C=CC(Cl)=CC2=4)CC1',1), # clopenthixol ('c1ccccc1-C(=O)-CCO',0), ('CC(=O)NCCC',0) ] self._runTest(data,Fragments.fr_HOCCN) def test20(self): data = [('c1ccccc1OC',1), ('c1ccccc1Oc2ccccc2',0), ('c1ccccc1OCC',0), ] self._runTest(data,Fragments.fr_methoxy) def test21(self): data = [('C/C(C(C)=O)=N\O',1), ('C(=N/OC(C(=O)O)(C)C)(/C1=CS[N+](=N1)C)C(N[C@@H]2C(N([C@@H]2C)S(O)(=O)=O)=O)=O',1), # aztreonam ('c1ccccc1OCC',0), ] self._runTest(data,Fragments.fr_oxime) def test22(self): data = [('CCCF',1), ('c1ccccc1C(C)(C)Br',1), ('c1ccccc1CC(C)(C)Cl',1), ] self._runTest(data,Fragments.fr_alkyl_halide) if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/UnitTestFragmentDescriptors.py", "copies": "1", "size": "8371", "license": "bsd-3-clause", "hash": 1416664396338389800, "line_mean": 35.2380952381, "line_max": 159, "alpha_frac": 0.482499104, "autogenerated": false, "ratio": 2.095893840761142, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3078392944761142, "avg_score": null, "num_lines": null }
"""unit testing code for graph-theoretical descriptors """ from __future__ import print_function from rdkit import RDConfig import unittest,os.path from rdkit import Chem from rdkit.Chem import GraphDescriptors,MolSurf,Lipinski,Crippen def feq(n1,n2,tol=1e-4): return abs(n1-n2)<=tol class TestCase(unittest.TestCase): def setUp(self): if doLong: print('\n%s: '%self.shortDescription(),end='') def testBertzCTShort(self): """ test calculation of Bertz 'C(T)' index """ data = [('C=CC=C',21.01955), ('O=CC=O',25.01955), ('FCC(=O)CF',46.7548875), ('O=C1C=CC(=O)C=C1',148.705216), ('C12C(F)=C(O)C(F)C1C(F)=C(O)C(F)2',315.250442), ('C12CC=CCC1C(=O)C3CC=CCC3C(=O)2',321.539522)] for smi,CT in data: m = Chem.MolFromSmiles(smi) newCT = GraphDescriptors.BertzCT(m, forceDMat = 1) assert feq(newCT,CT,1e-3),'mol %s (CT calc = %f) should have CT = %f'%(smi,newCT,CT) def _testBertzCTLong(self): """ test calculation of Bertz 'C(T)' index NOTE: this is a backwards compatibility test, because of the changes w.r.t. the treatment of aromatic atoms in the new version, we need to ignore molecules with aromatic rings... """ col = 1 with open(os.path.join(RDConfig.RDCodeDir,'Chem','test_data','PP_descrs_regress.2.csv'),'r') as inF: lineNum=0 for line in inF: lineNum+=1 if line[0] != '#': splitL = line.split(',') smi = splitL[0] try: m = Chem.MolFromSmiles(smi) except: m = None assert m,'line %d, smiles: %s'%(lineNum,smi) useIt=1 for atom in m.GetAtoms(): if atom.GetIsAromatic(): useIt=0 break if useIt: tgtVal = float(splitL[col]) try: val = GraphDescriptors.BertzCT(m) except: val = 666 assert feq(val,tgtVal,1e-4),'line %d, mol %s (CT calc = %f) should have CT = %f'%(lineNum,smi,val,tgtVal) def __testDesc(self,fileN,col,func): with open(os.path.join(RDConfig.RDCodeDir,'Chem','test_data',fileN),'r') as inF: lineNum=0 for line in inF: lineNum+=1 if line[0] != '#': splitL = line.split(',') smi = splitL[0] try: m = Chem.MolFromSmiles(smi) except: m = None assert m,'line %d, smiles: %s'%(lineNum,smi) useIt=1 if useIt: tgtVal = float(splitL[col]) if not feq(tgtVal,666.0): try: val = func(m) except: val = 666 assert feq(val,tgtVal,1e-4),'line %d, mol %s (calc = %f) should have val = %f'%(lineNum,smi,val,tgtVal) def testChi0Long(self): """ test calculation of Chi0 """ col = 2 self.__testDesc('PP_descrs_regress.csv',col,GraphDescriptors.Chi0) def _testChi0Long2(self): """ test calculation of Chi0 """ col = 2 self.__testDesc('PP_descrs_regress.2.csv',col,GraphDescriptors.Chi0) def testHallKierAlphaLong(self): """ test calculation of the Hall-Kier Alpha value """ col = 3 self.__testDesc('PP_descrs_regress.csv',col,GraphDescriptors.HallKierAlpha) def _testHallKierAlphaLong2(self): """ test calculation of the Hall-Kier Alpha value """ col = 3 self.__testDesc('PP_descrs_regress.2.csv',col,GraphDescriptors.HallKierAlpha) def testIpc(self): """ test calculation of Ipc. """ data = [('CCCCC',1.40564,11.24511),('CCC(C)C',1.37878, 9.65148),('CC(C)(C)C',0.72193,3.60964),('CN(CC)CCC',1.67982,31.91664),('C1CCCCC1',1.71997,34.39946),('CC1CCCCC1',1.68562,47.19725),('Cc1ccccc1',1.68562,47.19725),('CC(C)=C(C)C',1.36096,13.60964),('C#N',1.00000,2.00000),('OC#N',0.91830,2.75489)] for smi,res1,res2 in data: m = Chem.MolFromSmiles(smi) Ipc = GraphDescriptors.Ipc(m, forceDMat=1) Ipc_avg = GraphDescriptors.Ipc(m,avg = 1, forceDMat=1) assert feq(Ipc_avg,res1,1e-3),'mol %s (Ipc_avg=%f) should have Ipc_avg=%f'%(smi,Ipc_avg,res1) assert feq(Ipc,res2,1e-3),'mol %s (Ipc=%f) should have Ipc=%f'%(smi,Ipc,res2) Ipc = GraphDescriptors.Ipc(m) Ipc_avg = GraphDescriptors.Ipc(m,avg = 1) assert feq(Ipc_avg,res1,1e-3),'2nd pass: mol %s (Ipc_avg=%f) should have Ipc_avg=%f'%(smi,Ipc_avg,res1) assert feq(Ipc,res2,1e-3),'2nd pass: mol %s (Ipc=%f) should have Ipc=%f'%(smi,Ipc,res2) def _testIpcLong(self): """ test calculation of Ipc """ col = 4 self.__testDesc('PP_descrs_regress.csv',col,GraphDescriptors.Ipc) def _testIpcLong2(self): """ test calculation of Ipc """ col = 4 self.__testDesc('PP_descrs_regress.2.csv',col,GraphDescriptors.Ipc) def testKappa1(self): """ test calculation of the Hall-Kier kappa1 value corrected data from Tables 3 and 6 of Rev. Comp. Chem. vol 2, 367-422, (1991) """ data = [('C12CC2C3CC13',2.344), ('C1CCC12CC2',3.061), ('C1CCCCC1',4.167), ('CCCCCC',6.000), ('CCC(C)C1CCC(C)CC1',9.091), ('CC(C)CC1CCC(C)CC1',9.091), ('CC(C)C1CCC(C)CCC1',9.091) ] for smi,res in data: m = Chem.MolFromSmiles(smi) kappa = GraphDescriptors.Kappa1(m) assert feq(kappa,res,1e-3),'mol %s (kappa1=%f) should have kappa1=%f'%(smi,kappa,res) def testKappa2(self): """ test calculation of the Hall-Kier kappa2 value corrected data from Tables 5 and 6 of Rev. Comp. Chem. vol 2, 367-422, (1991) """ data = [ ('[C+2](C)(C)(C)(C)(C)C',0.667), ('[C+](C)(C)(C)(C)(CC)',1.240), ('C(C)(C)(C)(CCC)',2.3444), ('CC(C)CCCC',4.167), ('CCCCCCC',6.000), ('CCCCCC',5.000), ('CCCCCCC',6.000), ('C1CCCC1',1.440), ('C1CCCC1C',1.633), ('C1CCCCC1',2.222), ('C1CCCCCC1',3.061), ('CCCCC',4.00), ('CC=CCCC',4.740), ('C1=CN=CN1',0.884), ('c1ccccc1',1.606), ('c1cnccc1',1.552), ('n1ccncc1',1.500), ('CCCCF',3.930), ('CCCCCl',4.290), ('CCCCBr',4.480), ('CCC(C)C1CCC(C)CC1',4.133), ('CC(C)CC1CCC(C)CC1',4.133), ('CC(C)C1CCC(C)CCC1',4.133) ] for smi,res in data: #print smi m = Chem.MolFromSmiles(smi) kappa = GraphDescriptors.Kappa2(m) assert feq(kappa,res,1e-3),'mol %s (kappa2=%f) should have kappa2=%f'%(smi,kappa,res) def testKappa3(self): """ test calculation of the Hall-Kier kappa3 value corrected data from Tables 3 and 6 of Rev. Comp. Chem. vol 2, 367-422, (1991) """ data = [ ('C[C+](C)(C)(C)C(C)(C)C',2.000), ('CCC(C)C(C)(C)(CC)',2.380), ('CCC(C)CC(C)CC',4.500), ('CC(C)CCC(C)CC',5.878), ('CC(C)CCCC(C)C',8.000), ('CCC(C)C1CCC(C)CC1',2.500), ('CC(C)CC1CCC(C)CC1',3.265), ('CC(C)C1CCC(C)CCC1',2.844) ] for smi,res in data: m = Chem.MolFromSmiles(smi) kappa = GraphDescriptors.Kappa3(m) assert feq(kappa,res,1e-3),'mol %s (kappa3=%f) should have kappa3=%f'%(smi,kappa,res) def testKappa3Long(self): """ test calculation of kappa3 """ col = 5 self.__testDesc('PP_descrs_regress.csv',col,GraphDescriptors.Kappa3) def _testKappa3Long2(self): """ test calculation of kappa3 """ col = 5 self.__testDesc('PP_descrs_regress.2.csv',col,GraphDescriptors.Kappa3) def _testLabuteASALong(self): """ test calculation of Labute's ASA value """ col = 6 self.__testDesc('PP_descrs_regress.csv',col,lambda x:MolSurf.LabuteASA(x,includeHs=1)) def _testLabuteASALong2(self): """ test calculation of Labute's ASA value """ col = 6 self.__testDesc('PP_descrs_regress.2.csv',col,lambda x:MolSurf.LabuteASA(x,includeHs=1)) def _testTPSAShortNCI(self): " Short TPSA test " inName = RDConfig.RDDataDir+'/NCI/first_200.tpsa.csv' with open(inName,'r') as inF: lines = inF.readlines() for line in lines: if line[0] != '#': line.strip() smi,ans = line.split(',') ans = float(ans) mol = Chem.MolFromSmiles(smi) calc = MolSurf.TPSA(mol) assert feq(calc,ans),'bad TPSA for SMILES %s (%.2f != %.2f)'%(smi,calc,ans) def _testTPSALongNCI(self): " Long TPSA test " fileN = 'tpsa_regr.csv' with open(os.path.join(RDConfig.RDCodeDir,'Chem','test_data',fileN),'r') as inF: lines = inF.readlines() lineNo = 0 for line in lines: lineNo+=1 if line[0] != '#': line.strip() smi,ans = line.split(',') ans = float(ans) try: mol = Chem.MolFromSmiles(smi) except: import traceback traceback.print_exc() mol = None assert mol,"line %d, failed for smiles: %s"%(lineNo,smi) calc = MolSurf.TPSA(mol) assert feq(calc,ans),'line %d: bad TPSA for SMILES %s (%.2f != %.2f)'%(lineNo,smi,calc,ans) def testTPSALong(self): """ test calculation of TPSA """ col = 28 self.__testDesc('PP_descrs_regress.csv',col,MolSurf.TPSA) def _testTPSALong2(self): """ test calculation of TPSA """ col = 28 self.__testDesc('PP_descrs_regress.2.csv',col,MolSurf.TPSA) def _testLipinskiLong(self): """ test calculation of Lipinski params """ fName = 'PP_descrs_regress.csv' # we can't do H Acceptors for these pyridine-containing molecules # because the values will be wrong for EVERY one. #col = 29 #self.__testDesc(fName,col,Lipinski.NumHAcceptors) col = 30 self.__testDesc(fName,col,Lipinski.NumHDonors) col = 31 self.__testDesc(fName,col,Lipinski.NumHeteroatoms) col = 32 self.__testDesc(fName,col,Lipinski.NumRotatableBonds) def _testHAcceptorsLong(self): """ test calculation of Lipinski params """ fName = 'Block_regress.Lip.csv' col = 1 self.__testDesc(fName,col,Lipinski.NumHAcceptors) def _testHDonorsLong(self): """ test calculation of Lipinski params """ fName = 'Block_regress.Lip.csv' col = 2 self.__testDesc(fName,col,Lipinski.NumHDonors) def _testHeterosLong(self): """ test calculation of Lipinski params """ fName = 'Block_regress.Lip.csv' col = 3 self.__testDesc(fName,col,Lipinski.NumHeteroatoms) def _testRotBondsLong(self): """ test calculation of Lipinski params """ fName = 'Block_regress.Lip.csv' col = 4 self.__testDesc(fName,col,Lipinski.NumRotatableBonds) def _testLogPLong(self): """ test calculation of Lipinski params """ fName = 'PP_descrs_regress.csv' col = 33 self.__testDesc(fName,col,lambda x:Crippen.MolLogP(x,includeHs=1)) def _testLogPLong2(self): """ test calculation of Lipinski params """ fName = 'PP_descrs_regress.2.csv' col = 33 self.__testDesc(fName,col,lambda x:Crippen.MolLogP(x,includeHs=1)) def _testMOELong(self): """ test calculation of MOE-type descriptors """ fName = 'PP_descrs_regress.VSA.csv' col = 1 self.__testDesc(fName,col,MolSurf.SMR_VSA1) col = 2 self.__testDesc(fName,col,MolSurf.SMR_VSA10) col = 3 self.__testDesc(fName,col,MolSurf.SMR_VSA2) col = 4 self.__testDesc(fName,col,MolSurf.SMR_VSA3) col = 5 self.__testDesc(fName,col,MolSurf.SMR_VSA4) col = 6 self.__testDesc(fName,col,MolSurf.SMR_VSA5) col = 7 self.__testDesc(fName,col,MolSurf.SMR_VSA6) col = 8 self.__testDesc(fName,col,MolSurf.SMR_VSA7) col = 9 self.__testDesc(fName,col,MolSurf.SMR_VSA8) col = 10 self.__testDesc(fName,col,MolSurf.SMR_VSA9) col = 11 self.__testDesc(fName,col,MolSurf.SlogP_VSA1) col = 12 self.__testDesc(fName,col,MolSurf.SlogP_VSA10) col = 13 self.__testDesc(fName,col,MolSurf.SlogP_VSA11) col = 14 self.__testDesc(fName,col,MolSurf.SlogP_VSA12) def _testMOELong2(self): """ test calculation of MOE-type descriptors """ fName = 'PP_descrs_regress.VSA.2.csv' col = 1 self.__testDesc(fName,col,MolSurf.SMR_VSA1) col = 2 self.__testDesc(fName,col,MolSurf.SMR_VSA10) col = 11 self.__testDesc(fName,col,MolSurf.SlogP_VSA1) col = 12 self.__testDesc(fName,col,MolSurf.SlogP_VSA10) col = 13 self.__testDesc(fName,col,MolSurf.SlogP_VSA11) col = 14 self.__testDesc(fName,col,MolSurf.SlogP_VSA12) def testBalabanJ(self): """ test calculation of the Balaban J value J values are from Balaban's paper and have had roundoff errors and typos corrected. """ data = [# alkanes ('CC',1.0),('CCC',1.6330), ('CCCC',1.9747),('CC(C)C',2.3238), ('CCCCC',2.1906),('CC(C)CC',2.5396),('CC(C)(C)C',3.0237), ('CCCCCC',2.3391),('CC(C)CCC',2.6272),('CCC(C)CC',2.7542),('CC(C)(C)CC',3.1685), ('CC(C)C(C)C',2.9935), # cycloalkanes ('C1CCCCC1',2.0000), ('C1C(C)CCCC1',2.1229), ('C1C(CC)CCCC1',2.1250), ('C1C(C)C(C)CCC1',2.2794), ('C1C(C)CC(C)CC1',2.2307), ('C1C(C)CCC(C)C1',2.1924), ('C1C(CCC)CCCC1',2.0779), ('C1C(C(C)C)CCCC1',2.2284), ('C1C(CC)C(C)CCC1',2.2973), ('C1C(CC)CC(C)CC1',2.2317), ('C1C(CC)CCC(C)C1',2.1804), ('C1C(C)C(C)C(C)CC1',2.4133), ('C1C(C)C(C)CC(C)C1',2.3462), ('C1C(C)CC(C)CC1(C)',2.3409), # aromatics ('c1ccccc1',3.0000), ('c1c(C)cccc1',3.0215), ('c1c(CC)cccc1',2.8321), ('c1c(C)c(C)ccc1',3.1349), ('c1c(C)cc(C)cc1',3.0777), ('c1c(C)ccc(C)c1',3.0325), ('c1c(CCC)cccc1',2.6149), ('c1c(C(C)C)cccc1',2.8483), ('c1c(CC)c(C)ccc1',3.0065), ('c1c(CC)cc(C)cc1',2.9369), ('c1c(CC)ccc(C)c1',2.8816), ('c1c(C)c(C)c(C)cc1',3.2478), ('c1c(C)c(C)cc(C)c1',3.1717), ('c1c(C)cc(C)cc1(C)',3.1657) ] for smi,res in data: m = Chem.MolFromSmiles(smi) j = GraphDescriptors.BalabanJ(m,forceDMat=1) assert feq(j,res),'mol %s (J=%f) should have J=%f'%(smi,j,res) j = GraphDescriptors.BalabanJ(m) assert feq(j,res),'second pass: mol %s (J=%f) should have J=%f'%(smi,j,res) def _testBalabanJLong(self): """ test calculation of the balaban j value """ fName = 'PP_descrs_regress.rest.2.csv' col = 1 self.__testDesc(fName,col,GraphDescriptors.BalabanJ) def _testKappa1Long(self): """ test calculation of kappa1 """ fName = 'PP_descrs_regress.rest.2.csv' col = 31 self.__testDesc(fName,col,GraphDescriptors.Kappa1) def _testKappa2Long(self): """ test calculation of kappa2 """ fName = 'PP_descrs_regress.rest.2.csv' col = 32 self.__testDesc(fName,col,GraphDescriptors.Kappa2) def _testChi0Long(self): fName = 'PP_descrs_regress.rest.2.csv' col = 5 self.__testDesc(fName,col,GraphDescriptors.Chi0) def _testChi1Long(self): fName = 'PP_descrs_regress.rest.2.csv' col = 8 self.__testDesc(fName,col,GraphDescriptors.Chi1) def _testChi0v(self): """ test calculation of Chi0v """ data = [('CCCCCC',4.828),('CCC(C)CC',4.992),('CC(C)CCC',4.992), ('CC(C)C(C)C',5.155),('CC(C)(C)CC',5.207), ('CCCCCO',4.276),('CCC(O)CC',4.439),('CC(O)(C)CC',4.654),('c1ccccc1O',3.834), ('CCCl',2.841),('CCBr',3.671),('CCI',4.242)] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi0v(m) assert feq(chi,res,1e-3),'mol %s (Chi0v=%f) should have Chi0V=%f'%(smi,chi,res) def _testChi0vLong(self): fName = 'PP_descrs_regress.rest.2.csv' col = 7 self.__testDesc(fName,col,GraphDescriptors.Chi0v) def testChi1v(self): """ test calculation of Chi1v """ data = [('CCCCCC',2.914),('CCC(C)CC',2.808),('CC(C)CCC',2.770), ('CC(C)C(C)C',2.643),('CC(C)(C)CC',2.561), ('CCCCCO',2.523),('CCC(O)CC',2.489),('CC(O)(C)CC',2.284),('c1ccccc1O',2.134)] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi1v(m) assert feq(chi,res,1e-3),'mol %s (Chi1v=%f) should have Chi1V=%f'%(smi,chi,res) def _testChi1vLong(self): fName = 'PP_descrs_regress.rest.2.csv' col = 10 self.__testDesc(fName,col,GraphDescriptors.Chi1v) def testPathCounts(self): """ FIX: this should be in some other file """ data = [('CCCCCC',(6,5,4,3,2,1)), ('CCC(C)CC',(6,5,5,4,1,0)), ('CC(C)CCC',(6,5,5,3,2,0)), ('CC(C)C(C)C',(6,5,6,4,0,0)), ('CC(C)(C)CC',(6,5,7,3,0,0)), ('CCCCCO',(6,5,4,3,2,1)), ('CCC(O)CC',(6,5,5,4,1,0)), ('CC(O)(C)CC',(6,5,7,3,0,0)), ('c1ccccc1O',(7,7,8,8,8,8)), ] for smi,res in data: m = Chem.MolFromSmiles(smi) for i in range(1,6): cnt = len(Chem.FindAllPathsOfLengthN(m,i,useBonds=1)) assert cnt==res[i],(smi,i,cnt,res[i],Chem.FindAllPathsOfLengthN(m,i,useBonds=1)) cnt = len(Chem.FindAllPathsOfLengthN(m,i+1,useBonds=0)) assert cnt==res[i],(smi,i,cnt,res[i],Chem.FindAllPathsOfLengthN(m,i+1,useBonds=1)) def testChi2v(self): """ test calculation of Chi2v """ data = [('CCCCCC',1.707),('CCC(C)CC',1.922),('CC(C)CCC',2.183), ('CC(C)C(C)C',2.488),('CC(C)(C)CC',2.914), ('CCCCCO',1.431),('CCC(O)CC',1.470),('CC(O)(C)CC',2.166),('c1ccccc1O',1.336), ] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi2v(m) assert feq(chi,res,1e-3),'mol %s (Chi2v=%f) should have Chi2V=%f'%(smi,chi,res) def _testChi2vLong(self): fName = 'PP_descrs_regress.rest.2.csv' col = 12 self.__testDesc(fName,col,GraphDescriptors.Chi2v) def testChi3v(self): """ test calculation of Chi3v """ data = [('CCCCCC',0.957),('CCC(C)CC',1.394),('CC(C)CCC',0.866),('CC(C)C(C)C',1.333),('CC(C)(C)CC',1.061), ('CCCCCO',0.762),('CCC(O)CC',0.943),('CC(O)(C)CC',0.865),('c1ccccc1O',0.756)] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi3v(m) assert feq(chi,res,1e-3),'mol %s (Chi3v=%f) should have Chi3V=%f'%(smi,chi,res) def _testChi3vLong(self): fName = 'PP_descrs_regress.rest.2.csv' col = 14 self.__testDesc(fName,col,GraphDescriptors.Chi3v) def testChi4v(self): """ test calculation of Chi4v """ data = [('CCCCCC',0.500),('CCC(C)CC',0.289),('CC(C)CCC',0.577), ('CC(C)C(C)C',0.000),('CC(C)(C)CC',0.000), ('CCCCCO',0.362),('CCC(O)CC',0.289),('CC(O)(C)CC',0.000),('c1ccccc1O',0.428)] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi4v(m) assert feq(chi,res,1e-3),'mol %s (Chi4v=%f) should have Chi4V=%f'%(smi,chi,res) def testChi5v(self): """ test calculation of Chi5v """ data = [('CCCCCC',0.250),('CCC(C)CC',0.000),('CC(C)CCC',0.000), ('CC(C)C(C)C',0.000),('CC(C)(C)CC',0.000), ('CCCCCO',0.112),('CCC(O)CC',0.000),('CC(O)(C)CC',0.000),('c1ccccc1O',0.242)] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.ChiNv_(m,5) assert feq(chi,res,1e-3),'mol %s (Chi5v=%f) should have Chi5V=%f'%(smi,chi,res) def testChi0n(self): """ test calculation of Chi0n """ data = [('CCCCCC',4.828),('CCC(C)CC',4.992),('CC(C)CCC',4.992), ('CC(C)C(C)C',5.155),('CC(C)(C)CC',5.207), ('CCCCCO',4.276),('CCC(O)CC',4.439),('CC(O)(C)CC',4.654),('c1ccccc1O',3.834), ('CCCl',2.085),('CCBr',2.085),('CCI',2.085),] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi0n(m) assert feq(chi,res,1e-3),'mol %s (Chi0n=%f) should have Chi0n=%f'%(smi,chi,res) def _testChi0nLong(self): fName = 'PP_descrs_regress.rest.2.csv' col = 6 self.__testDesc(fName,col,GraphDescriptors.Chi0n) def testChi1n(self): """ test calculation of Chi1n """ data = [('CCCCCC',2.914),('CCC(C)CC',2.808),('CC(C)CCC',2.770), ('CC(C)C(C)C',2.643),('CC(C)(C)CC',2.561), ('CCCCCO',2.523),('CCC(O)CC',2.489),('CC(O)(C)CC',2.284),('c1ccccc1O',2.134)] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi1n(m) assert feq(chi,res,1e-3),'mol %s (Chi1n=%f) should have Chi1N=%f'%(smi,chi,res) def _testChi1nLong(self): fName = 'PP_descrs_regress.rest.2.csv' col = 9 self.__testDesc(fName,col,GraphDescriptors.Chi1n) def testChi2n(self): """ test calculation of Chi2n """ data = [('CCCCCC',1.707),('CCC(C)CC',1.922),('CC(C)CCC',2.183), ('CC(C)C(C)C',2.488),('CC(C)(C)CC',2.914), ('CCCCCO',1.431),('CCC(O)CC',1.470),('CC(O)(C)CC',2.166),('c1ccccc1O',1.336)] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi2n(m) assert feq(chi,res,1e-3),'mol %s (Chi2n=%f) should have Chi2N=%f'%(smi,chi,res) def _testChi2nLong(self): fName = 'PP_descrs_regress.rest.2.csv' col = 11 self.__testDesc(fName,col,GraphDescriptors.Chi2n) def testChi3n(self): """ test calculation of Chi3n """ data = [('CCCCCC',0.957),('CCC(C)CC',1.394),('CC(C)CCC',0.866),('CC(C)C(C)C',1.333),('CC(C)(C)CC',1.061), ('CCCCCO',0.762),('CCC(O)CC',0.943),('CC(O)(C)CC',0.865),('c1ccccc1O',0.756)] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi3n(m) assert feq(chi,res,1e-3),'mol %s (Chi3n=%f) should have Chi3N=%f'%(smi,chi,res) def _testChi3nLong(self): fName = 'PP_descrs_regress.rest.2.csv' col = 13 self.__testDesc(fName,col,GraphDescriptors.Chi3n) def testChi4n(self): """ test calculation of Chi4n """ data = [('CCCCCC',0.500),('CCC(C)CC',0.289),('CC(C)CCC',0.577), ('CC(C)C(C)C',0.000),('CC(C)(C)CC',0.000), ('CCCCCO',0.362),('CCC(O)CC',0.289),('CC(O)(C)CC',0.000),('c1ccccc1O',0.428)] for smi,res in data: m = Chem.MolFromSmiles(smi) chi = GraphDescriptors.Chi4n(m) assert feq(chi,res,1e-3),'mol %s (Chi4n=%f) should have Chi4N=%f'%(smi,chi,res) def testIssue125(self): """ test an issue with calculating BalabanJ """ smi = 'O=C(OC)C1=C(C)NC(C)=C(C(OC)=O)C1C2=CC=CC=C2[N+]([O-])=O' m1 = Chem.MolFromSmiles(smi) m2 = Chem.MolFromSmiles(smi) Chem.MolToSmiles(m1) j1=GraphDescriptors.BalabanJ(m1) j2=GraphDescriptors.BalabanJ(m2) assert feq(j1,j2) def testOrderDepend(self): """ test order dependence of some descriptors: """ data = [('C=CC=C',21.01955,2.73205), ('O=CC=O',25.01955,2.73205), ('FCC(=O)CF',46.7548875,2.98816), ('O=C1C=CC(=O)C=C1',148.705216,2.8265), ('C12C(F)=C(O)C(F)C1C(F)=C(O)C(F)2',315.250442,2.4509), ('C12CC=CCC1C(=O)C3CC=CCC3C(=O)2',321.539522,1.95986)] for smi,CT,bal in data: m = Chem.MolFromSmiles(smi) newBal = GraphDescriptors.BalabanJ(m, forceDMat = 1) assert feq(newBal,bal,1e-4),'mol %s %f!=%f'%(smi,newBal,bal) m = Chem.MolFromSmiles(smi) newCT = GraphDescriptors.BertzCT(m, forceDMat = 1) assert feq(newCT,CT,1e-4),'mol %s (CT calc = %f) should have CT = %f'%(smi,newCT,CT) m = Chem.MolFromSmiles(smi) newCT = GraphDescriptors.BertzCT(m, forceDMat = 1) assert feq(newCT,CT,1e-4),'mol %s (CT calc = %f) should have CT = %f'%(smi,newCT,CT) newBal = GraphDescriptors.BalabanJ(m, forceDMat = 1) assert feq(newBal,bal,1e-4),'mol %s %f!=%f'%(smi,newBal,bal) m = Chem.MolFromSmiles(smi) newBal = GraphDescriptors.BalabanJ(m, forceDMat = 1) assert feq(newBal,bal,1e-4),'mol %s %f!=%f'%(smi,newBal,bal) newCT = GraphDescriptors.BertzCT(m, forceDMat = 1) assert feq(newCT,CT,1e-4),'mol %s (CT calc = %f) should have CT = %f'%(smi,newCT,CT) 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": "soerendip42/rdkit", "path": "rdkit/Chem/UnitTestGraphDescriptors.2.py", "copies": "3", "size": "24674", "license": "bsd-3-clause", "hash": -6053846350987624000, "line_mean": 30.6333333333, "line_max": 302, "alpha_frac": 0.5775310043, "autogenerated": false, "ratio": 2.5072655217965654, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4584796526096566, "avg_score": null, "num_lines": null }
""" unit testing code for Lipinski parameter calculation This provides a workout for the SMARTS matcher """ from __future__ import print_function from rdkit import RDConfig import unittest,os from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import Lipinski, rdMolDescriptors NonStrict = "NUM_ROTATABLEBONDS_O" Strict = "NUM_ROTATABLEBONDS" class TestCase(unittest.TestCase): def setUp(self): print('\n%s: '%self.shortDescription(),end='') self.inFileName = '%s/NCI/first_200.props.sdf'%(RDConfig.RDDataDir) def test1(self): " testing first 200 mols from NCI " # figure out which rotor version we are using m = Chem.MolFromSmiles("CC(C)(C)c1cc(O)c(cc1O)C(C)(C)C") if Lipinski.NumRotatableBonds(m) == 2: rot_prop = NonStrict else: rot_prop = Strict suppl = Chem.SDMolSupplier(self.inFileName) idx = 1 oldDonorSmarts = Chem.MolFromSmarts('[NH1,NH2,OH1]') OldDonorCount = lambda x,y=oldDonorSmarts:Lipinski._NumMatches(x,y) oldAcceptorSmarts = Chem.MolFromSmarts('[N,O]') OldAcceptorCount = lambda x,y=oldAcceptorSmarts:Lipinski._NumMatches(x,y) for m in suppl: if m: calc = Lipinski.NHOHCount(m) orig = int(m.GetProp('NUM_LIPINSKIHDONORS')) assert calc==orig,'bad num h donors for mol %d (%s): %d != %d'%(idx,m.GetProp('SMILES'),calc,orig) calc = Lipinski.NOCount(m) orig = int(m.GetProp('NUM_LIPINSKIHACCEPTORS')) assert calc==orig,'bad num h acceptors for mol %d (%s): %d != %d'%(idx,m.GetProp('SMILES'),calc,orig) calc = Lipinski.NumHDonors(m) orig = int(m.GetProp('NUM_HDONORS')) assert calc==orig,'bad num h donors for mol %d (%s): %d != %d'%(idx,m.GetProp('SMILES'),calc,orig) calc = Lipinski.NumHAcceptors(m) orig = int(m.GetProp('NUM_HACCEPTORS')) assert calc==orig,'bad num h acceptors for mol %d (%s): %d != %d'%(idx,m.GetProp('SMILES'),calc,orig) calc = Lipinski.NumHeteroatoms(m) orig = int(m.GetProp('NUM_HETEROATOMS')) assert calc==orig,'bad num heteroatoms for mol %d (%s): %d != %d'%(idx,m.GetProp('SMILES'),calc,orig) calc = Lipinski.NumRotatableBonds(m) orig = int(m.GetProp(rot_prop)) assert calc==orig,'bad num rotors for mol %d (%s): %d != %d'%(idx,m.GetProp('SMILES'),calc,orig) # test the underlying numrotatable bonds calc = rdMolDescriptors.CalcNumRotatableBonds(m, rdMolDescriptors.NumRotatableBondsOptions.NonStrict) orig = int(m.GetProp(NonStrict)) assert calc==orig,'bad num rotors for mol %d (%s): %d != %d'%(idx,m.GetProp('SMILES'),calc,orig) calc = rdMolDescriptors.CalcNumRotatableBonds(m, rdMolDescriptors.NumRotatableBondsOptions.Strict) orig = int(m.GetProp(Strict)) assert calc==orig,'bad num rotors for mol %d (%s): %d != %d'%(idx,m.GetProp('SMILES'),calc,orig) idx += 1 def testIssue2183420(self): " testing a problem with the acceptor definition " self.assertTrue(Lipinski.NumHAcceptors(Chem.MolFromSmiles('NC'))==1) self.assertTrue(Lipinski.NumHAcceptors(Chem.MolFromSmiles('CNC'))==1) self.assertTrue(Lipinski.NumHAcceptors(Chem.MolFromSmiles('CN(C)C'))==1) self.assertTrue(Lipinski.NumHAcceptors(Chem.MolFromSmiles('NC(=O)'))==1) self.assertTrue(Lipinski.NumHAcceptors(Chem.MolFromSmiles('NC(=O)C'))==1) self.assertTrue(Lipinski.NumHAcceptors(Chem.MolFromSmiles('CNC(=O)'))==1) self.assertTrue(Lipinski.NumHAcceptors(Chem.MolFromSmiles('CNC(=O)C'))==1) self.assertTrue(Lipinski.NumHAcceptors(Chem.MolFromSmiles('O=CNC(=O)C'))==2) self.assertTrue(Lipinski.NumHAcceptors(Chem.MolFromSmiles('O=C(C)NC(=O)C'))==2) if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/UnitTestLipinski.py", "copies": "1", "size": "4077", "license": "bsd-3-clause", "hash": 8906459942523702000, "line_mean": 41.0309278351, "line_max": 109, "alpha_frac": 0.6661761099, "autogenerated": false, "ratio": 2.794379712131597, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39605558220315973, "avg_score": null, "num_lines": null }
""" unit testing code for molecule suppliers """ from rdkit import RDConfig import unittest,cPickle,os from rdkit import Chem class TestCase(unittest.TestCase): def setUp(self): self._files=[] def tearDown(self): for fileN in self._files: try: os.unlink(fileN) except OSError: pass def test1SDSupplier(self): fileN = os.path.join(RDConfig.RDCodeDir,'VLib','NodeLib','test_data','NCI_aids.10.sdf') suppl = Chem.SDMolSupplier(fileN) ms = [x for x in suppl] assert len(ms)==10 # test repeating: ms = [x for x in suppl] assert len(ms)==10 # test reset: suppl.reset() m = suppl.next() assert m.GetProp('_Name')=='48' assert m.GetProp('NSC')=='48' assert m.GetProp('CAS_RN')=='15716-70-8' m = suppl.next() assert m.GetProp('_Name')=='78' assert m.GetProp('NSC')=='78' assert m.GetProp('CAS_RN')=='6290-84-2' suppl.reset() for i in range(10): m = suppl.next() try: m = suppl.next() except StopIteration: ok=1 else: ok=0 assert ok def test2SmilesSupplier(self): fileN = os.path.join(RDConfig.RDCodeDir,'VLib','NodeLib','test_data','pgp_20.txt') suppl = Chem.SmilesMolSupplier(fileN,delimiter='\t',smilesColumn=2, nameColumn=1,titleLine=1) ms = [x for x in suppl] assert len(ms)==20 # test repeating: ms = [x for x in suppl] assert len(ms)==20 # test reset: suppl.reset() m = suppl.next() assert m.GetProp('_Name')=='ALDOSTERONE' assert m.GetProp('ID')=='RD-PGP-0001' m = suppl.next() assert m.GetProp('_Name')=='AMIODARONE' assert m.GetProp('ID')=='RD-PGP-0002' suppl.reset() for i in range(20): m = suppl.next() try: m = suppl.next() except StopIteration: ok=1 else: ok=0 assert ok def test3SmilesSupplier(self): txt="""C1CC1,1 CC(=O)O,3 fail,4 CCOC,5 """ import tempfile fileN = tempfile.mktemp('.csv') open(fileN,'w+').write(txt) self._files.append(fileN) suppl = Chem.SmilesMolSupplier(fileN,delimiter=',',smilesColumn=0, nameColumn=1,titleLine=0) ms = [x for x in suppl] while ms.count(None): ms.remove(None) assert len(ms)==3 if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/UnitTestSuppliers.py", "copies": "2", "size": "2680", "license": "bsd-3-clause", "hash": -6046542816694804000, "line_mean": 22.9285714286, "line_max": 91, "alpha_frac": 0.5873134328, "autogenerated": false, "ratio": 3.055872291904219, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4643185724704219, "avg_score": null, "num_lines": null }
""" utility functionality for clustering molecules using fingerprints includes a command line app for clustering Sample Usage: python ClusterMols.py -d data.gdb -t daylight_sig \ --idName="CAS_TF" -o clust1.pkl \ --actTable="dop_test" --actName="moa_quant" """ from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbInfo,DbUtils from rdkit.ML.Data import DataUtils from rdkit.ML.Cluster import Clusters from rdkit.ML.Cluster import Murtagh import sys,cPickle from rdkit.Chem.Fingerprints import FingerprintMols,MolSimilarity from rdkit import DataStructs import numpy _cvsVersion="$Id$" idx1 = _cvsVersion.find(':')+1 idx2 = _cvsVersion.rfind('$') __VERSION_STRING="%s"%(_cvsVersion[idx1:idx2]) message=FingerprintMols.message error=FingerprintMols.error def GetDistanceMatrix(data,metric,isSimilarity=1): """ data should be a list of tuples with fingerprints in position 1 (the rest of the elements of the tuple are not important) Returns the symmetric distance matrix (see ML.Cluster.Resemblance for layout documentation) """ nPts = len(data) res = numpy.zeros((nPts*(nPts-1)/2),numpy.float) nSoFar=0 for col in xrange(1,nPts): for row in xrange(col): fp1 = data[col][1] fp2 = data[row][1] if fp1.GetNumBits()>fp2.GetNumBits(): fp1 = DataStructs.FoldFingerprint(fp1,fp1.GetNumBits()/fp2.GetNumBits()) elif fp2.GetNumBits()>fp1.GetNumBits(): fp2 = DataStructs.FoldFingerprint(fp2,fp2.GetNumBits()/fp1.GetNumBits()) sim = metric(fp1,fp2) if isSimilarity: sim = 1.-sim res[nSoFar] = sim nSoFar += 1 return res def ClusterPoints(data,metric,algorithmId,haveLabels=False,haveActs=True,returnDistances=False): message('Generating distance matrix.\n') dMat = GetDistanceMatrix(data,metric) message('Clustering\n') clustTree = Murtagh.ClusterData(dMat,len(data),algorithmId, isDistData=1)[0] acts = [] if haveActs and len(data[0])>2: # we've got activities... use them: acts = [int(x[2]) for x in data] if not haveLabels: labels = ['Mol: %s'%str(x[0]) for x in data] else: labels = [x[0] for x in data] clustTree._ptLabels = labels if acts: clustTree._ptValues = acts for pt in clustTree.GetPoints(): idx = pt.GetIndex()-1 pt.SetName(labels[idx]) if acts: try: pt.SetData(int(acts[idx])) except: pass if not returnDistances: return clustTree else: return clustTree,dMat def ClusterFromDetails(details): """ Returns the cluster tree """ data = MolSimilarity.GetFingerprints(details) if details.maxMols > 0: data = data[:details.maxMols] if details.outFileName: try: outF = open(details.outFileName,'wb+') except IOError: error("Error: could not open output file %s for writing\n"%(details.outFileName)) return None else: outF = None if not data: return None clustTree = ClusterPoints(data,details.metric,details.clusterAlgo, haveLabels=0,haveActs=1) if outF: cPickle.dump(clustTree,outF) return clustTree _usageDoc=""" Usage: ClusterMols.py [args] <fName> If <fName> is provided and no tableName is specified (see below), data will be read from the text file <fName>. Text files delimited with either commas (extension .csv) or tabs (extension .txt) are supported. Command line arguments are: - -d _dbName_: set the name of the database from which to pull input fingerprint information. - -t _tableName_: set the name of the database table from which to pull input fingerprint information - --idName=val: sets the name of the id column in the input database. Default is *ID*. - -o _outFileName_: name of the output file (output will be a pickle (.pkl) file with the cluster tree) - --actTable=val: name of table containing activity values (used to color points in the cluster tree). - --actName=val: name of column with activities in the activity table. The values in this column should either be integers or convertible into integers. - --SLINK: use the single-linkage clustering algorithm (default is Ward's minimum variance) - --CLINK: use the complete-linkage clustering algorithm (default is Ward's minimum variance) - --UPGMA: use the group-average clustering algorithm (default is Ward's minimum variance) - --dice: use the DICE similarity metric instead of Tanimoto - --cosine: use the cosine similarity metric instead of Tanimoto - --fpColName=val: name to use for the column which stores fingerprints (in pickled format) in the input db table. Default is *AutoFragmentFP* - --minPath=val: minimum path length to be included in fragment-based fingerprints. Default is *2*. - --maxPath=val: maximum path length to be included in fragment-based fingerprints. Default is *7*. - --nBitsPerHash: number of bits to be set in the output fingerprint for each fragment. Default is *4*. - --discrim: use of path-based discriminators to hash bits. Default is *false*. - -V: include valence information in the fingerprints Default is *false*. - -H: include Hs in the fingerprint Default is *false*. - --useMACCS: use the public MACCS keys to do the fingerprinting (instead of a daylight-type fingerprint) """ if __name__ == '__main__': message("This is ClusterMols version %s\n\n"%(__VERSION_STRING)) FingerprintMols._usageDoc=_usageDoc details = FingerprintMols.ParseArgs() ClusterFromDetails(details)
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Fingerprints/ClusterMols.py", "copies": "2", "size": "6021", "license": "bsd-3-clause", "hash": 8993781663323533000, "line_mean": 30.1968911917, "line_max": 96, "alpha_frac": 0.6799534961, "autogenerated": false, "ratio": 3.5564087418783226, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5236362237978323, "avg_score": null, "num_lines": null }
""" utility functionality for fingerprinting sets of molecules includes a command line app for working with fingerprints and databases Sample Usage: python FingerprintMols.py -d data.gdb \ -t 'raw_dop_data' --smilesName="Structure" --idName="Mol_ID" \ --outTable="daylight_sig" """ from __future__ import print_function from rdkit import Chem from rdkit.Chem import MACCSkeys from rdkit.ML.Cluster import Murtagh from rdkit import DataStructs import sys from rdkit.six.moves import cPickle _cvsVersion = "$Id$" idx1 = _cvsVersion.find(':') + 1 idx2 = _cvsVersion.rfind('$') __VERSION_STRING = "%s" % (_cvsVersion[idx1:idx2]) def error(msg): sys.stderr.write(msg) def message(msg): sys.stderr.write(msg) def GetRDKFingerprint(mol): """ uses default parameters """ details = FingerprinterDetails() return apply(FingerprintMol, (mol, ), details.__dict__) def FoldFingerprintToTargetDensity(fp, **fpArgs): nOn = fp.GetNumOnBits() nTot = fp.GetNumBits() while (float(nOn) / nTot < fpArgs['tgtDensity']): if nTot / 2 > fpArgs['minSize']: fp = DataStructs.FoldFingerprint(fp, 2) nOn = fp.GetNumOnBits() nTot = fp.GetNumBits() else: break return fp def FingerprintMol(mol, fingerprinter=Chem.RDKFingerprint, **fpArgs): if not fpArgs: details = FingerprinterDetails() fpArgs = details.__dict__ if fingerprinter != Chem.RDKFingerprint: fp = fingerprinter(mol, **fpArgs) fp = FoldFingerprintToTargetDensity(fp, **fpArgs) else: fp = fingerprinter(mol, fpArgs['minPath'], fpArgs['maxPath'], fpArgs['fpSize'], fpArgs['bitsPerHash'], fpArgs['useHs'], fpArgs['tgtDensity'], fpArgs['minSize']) return fp def FingerprintsFromSmiles(dataSource, idCol, smiCol, fingerprinter=Chem.RDKFingerprint, reportFreq=10, maxMols=-1, **fpArgs): """ fpArgs are passed as keyword arguments to the fingerprinter Returns a list of 2-tuples: (id,fp) """ res = [] nDone = 0 for entry in dataSource: id, smi = str(entry[idCol]), str(entry[smiCol]) mol = Chem.MolFromSmiles(smi) if mol is not None: fp = FingerprintMol(mol, fingerprinter, **fpArgs) res.append((id, fp)) nDone += 1 if reportFreq > 0 and not nDone % reportFreq: message('Done %d molecules\n' % (nDone)) if maxMols > 0 and nDone >= maxMols: break else: error('Problems parsing SMILES: %s\n' % smi) return res def FingerprintsFromMols(mols, fingerprinter=Chem.RDKFingerprint, reportFreq=10, maxMols=-1, **fpArgs): """ fpArgs are passed as keyword arguments to the fingerprinter Returns a list of 2-tuples: (id,fp) """ res = [] nDone = 0 for id, mol in mols: if mol: fp = FingerprintMol(mol, fingerprinter, **fpArgs) res.append((id, fp)) nDone += 1 if reportFreq > 0 and not nDone % reportFreq: message('Done %d molecules\n' % (nDone)) if maxMols > 0 and nDone >= maxMols: break else: error('Problems parsing SMILES: %s\n' % smi) return res def FingerprintsFromPickles(dataSource, idCol, pklCol, fingerprinter=Chem.RDKFingerprint, reportFreq=10, maxMols=-1, **fpArgs): """ fpArgs are passed as keyword arguments to the fingerprinter Returns a list of 2-tuples: (id,fp) """ res = [] nDone = 0 for entry in dataSource: id, pkl = str(entry[idCol]), str(entry[pklCol]) mol = Chem.Mol(pkl) if mol is not None: fp = FingerprintMol(mol, fingerprinter, **fpArgs) res.append((id, fp)) nDone += 1 if reportFreq > 0 and not nDone % reportFreq: message('Done %d molecules\n' % (nDone)) if maxMols > 0 and nDone >= maxMols: break else: error('Problems parsing pickle for id: %s\n' % id) return res def FingerprintsFromDetails(details, reportFreq=10): data = None if details.dbName and details.tableName: from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbInfo from rdkit.ML.Data import DataUtils try: conn = DbConnect(details.dbName, details.tableName) except Exception: import traceback error('Problems establishing connection to database: %s|%s\n' % (details.dbName, details.tableName)) traceback.print_exc() if not details.idName: details.idName = DbInfo.GetColumnNames(details.dbName, details.tableName)[0] dataSet = DataUtils.DBToData(details.dbName, details.tableName, what='%s,%s' % (details.idName, details.smilesName)) idCol = 0 smiCol = 1 elif details.inFileName and details.useSmiles: from rdkit.ML.Data import DataUtils conn = None if not details.idName: details.idName = 'ID' try: dataSet = DataUtils.TextFileToData(details.inFileName, onlyCols=[details.idName, details.smilesName]) except IOError: import traceback error('Problems reading from file %s\n' % (details.inFileName)) traceback.print_exc() idCol = 0 smiCol = 1 elif details.inFileName and details.useSD: conn = None dataset = None if not details.idName: details.idName = 'ID' dataSet = [] try: s = Chem.SDMolSupplier(details.inFileName) except Exception: import traceback error('Problems reading from file %s\n' % (details.inFileName)) traceback.print_exc() else: while 1: try: m = s.next() except StopIteration: break if m: dataSet.append(m) if reportFreq > 0 and not len(dataSet) % reportFreq: message('Read %d molecules\n' % (len(dataSet))) if details.maxMols > 0 and len(dataSet) >= details.maxMols: break for i, mol in enumerate(dataSet): if mol.HasProp(details.idName): nm = mol.GetProp(details.idName) else: nm = mol.GetProp('_Name') dataSet[i] = (nm, mol) else: dataSet = None fps = None if dataSet and not details.useSD: data = dataSet.GetNamedData() if not details.molPklName: fps = apply(FingerprintsFromSmiles, (data, idCol, smiCol), details.__dict__) else: fps = apply(FingerprintsFromPickles, (data, idCol, smiCol), details.__dict__) elif dataSet and details.useSD: fps = apply(FingerprintsFromMols, (dataSet, ), details.__dict__) if fps: if details.outFileName: outF = open(details.outFileName, 'wb+') for i in range(len(fps)): cPickle.dump(fps[i], outF) outF.close() dbName = details.outDbName or details.dbName if details.outTableName and dbName: from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbInfo, DbUtils, DbModule conn = DbConnect(dbName) # # We don't have a db open already, so we'll need to figure out # the types of our columns... # colTypes = DbUtils.TypeFinder(data, len(data), len(data[0])) typeStrs = DbUtils.GetTypeStrings([details.idName, details.smilesName], colTypes, keyCol=details.idName) cols = '%s, %s %s' % (typeStrs[0], details.fpColName, DbModule.binaryTypeName) # FIX: we should really check to see if the table # is already there and, if so, add the appropriate # column. # # create the new table # if details.replaceTable or \ details.outTableName.upper() not in [x.upper() for x in conn.GetTableNames()]: conn.AddTable(details.outTableName, cols) # # And add the data # for id, fp in fps: tpl = id, DbModule.binaryHolder(fp.ToBinary()) conn.InsertData(details.outTableName, tpl) conn.Commit() return fps # ------------------------------------------------ # # Command line parsing stuff # # ------------------------------------------------ class FingerprinterDetails(object): """ class for storing the details of a fingerprinting run, generates sensible defaults on construction """ def __init__(self): self._fingerprinterInit() self._screenerInit() self._clusterInit() def _fingerprinterInit(self): self.fingerprinter = Chem.RDKFingerprint self.fpColName = "AutoFragmentFP" self.idName = '' self.dbName = '' self.outDbName = '' self.tableName = '' self.minSize = 64 self.fpSize = 2048 self.tgtDensity = 0.3 self.minPath = 1 self.maxPath = 7 self.discrimHash = 0 self.useHs = 0 self.useValence = 0 self.bitsPerHash = 2 self.smilesName = 'SMILES' self.maxMols = -1 self.outFileName = '' self.outTableName = '' self.inFileName = '' self.replaceTable = True self.molPklName = '' self.useSmiles = True self.useSD = False def _screenerInit(self): self.metric = DataStructs.TanimotoSimilarity self.doScreen = '' self.topN = 10 self.screenThresh = 0.75 self.doThreshold = 0 self.smilesTableName = '' self.probeSmiles = '' self.probeMol = None self.noPickle = 0 def _clusterInit(self): self.clusterAlgo = Murtagh.WARDS self.actTableName = '' self.actName = '' def GetMetricName(self): if self.metric == DataStructs.TanimotoSimilarity: return 'Tanimoto' elif self.metric == DataStructs.DiceSimilarity: return 'Dice' elif self.metric == DataStructs.CosineSimilarity: return 'Cosine' elif self.metric: return self.metric else: return 'Unknown' def SetMetricFromName(self, name): name = name.upper() if name == "TANIMOTO": self.metric = DataStructs.TanimotoSimilarity elif name == "DICE": self.metric = DataStructs.DiceSimilarity elif name == "COSINE": self.metric = DataStructs.CosineSimilarity def Usage(): """ prints a usage string and exits """ print(_usageDoc) sys.exit(-1) _usageDoc = """ Usage: FingerprintMols.py [args] <fName> If <fName> is provided and no tableName is specified (see below), data will be read from the text file <fName>. Text files delimited with either commas (extension .csv) or tabs (extension .txt) are supported. Command line arguments are: - -d _dbName_: set the name of the database from which to pull input molecule information. If output is going to a database, this will also be used for that unless the --outDbName option is used. - -t _tableName_: set the name of the database table from which to pull input molecule information - --smilesName=val: sets the name of the SMILES column in the input database. Default is *SMILES*. - --useSD: Assume that the input file is an SD file, not a SMILES table. - --idName=val: sets the name of the id column in the input database. Defaults to be the name of the first db column (or *ID* for text files). - -o _outFileName_: name of the output file (output will be a pickle file with one label,fingerprint entry for each molecule). - --outTable=val: name of the output db table used to store fingerprints. If this table already exists, it will be replaced. - --outDbName: name of output database, if it's being used. Defaults to be the same as the input db. - --fpColName=val: name to use for the column which stores fingerprints (in pickled format) in the output db table. Default is *AutoFragmentFP* - --maxSize=val: base size of the fingerprints to be generated Default is *2048* - --minSize=val: minimum size of the fingerprints to be generated (limits the amount of folding that happens). Default is *64* - --density=val: target bit density in the fingerprint. The fingerprint will be folded until this density is reached. Default is *0.3* - --minPath=val: minimum path length to be included in fragment-based fingerprints. Default is *1*. - --maxPath=val: maximum path length to be included in fragment-based fingerprints. Default is *7*. - --nBitsPerHash: number of bits to be set in the output fingerprint for each fragment. Default is *2*. - --discrim: use of path-based discriminators to hash bits. Default is *false*. - -V: include valence information in the fingerprints Default is *false*. - -H: include Hs in the fingerprint Default is *false*. - --maxMols=val: sets the maximum number of molecules to be fingerprinted. - --useMACCS: use the public MACCS keys to do the fingerprinting (instead of a daylight-type fingerprint) """ def ParseArgs(details=None): """ parses the command line arguments and returns a _FingerprinterDetails_ instance with the results. **Note**: - If you make modifications here, please update the global _usageDoc string so the Usage message is up to date. - This routine is used by both the fingerprinter, the clusterer and the screener; not all arguments make sense for all applications. """ import sys, getopt args = sys.argv[1:] try: args, extras = getopt.getopt(args, 'HVs:d:t:o:h', [ 'minSize=', 'maxSize=', 'density=', 'minPath=', 'maxPath=', 'bitsPerHash=', 'smilesName=', 'molPkl=', 'useSD', 'idName=', 'discrim', 'outTable=', 'outDbName=', 'fpColName=', 'maxMols=', 'useMACCS', 'keepTable', # SCREENING: 'smilesTable=', 'doScreen=', 'topN=', 'thresh=', 'smiles=', 'dice', 'cosine', # CLUSTERING: 'actTable=', 'actName=', 'SLINK', 'CLINK', 'UPGMA', ]) except Exception: import traceback traceback.print_exc() Usage() if details is None: details = FingerprinterDetails() if len(extras): details.inFileName = extras[0] for arg, val in args: if arg == '-H': details.useHs = 1 elif arg == '-V': details.useValence = 1 elif arg == '-d': details.dbName = val elif arg == '-t': details.tableName = val elif arg == '-o': details.outFileName = val elif arg == '--minSize': details.minSize = int(val) elif arg == '--maxSize': details.fpSize = int(val) elif arg == '--density': details.tgtDensity = float(val) elif arg == '--outTable': details.outTableName = val elif arg == '--outDbName': details.outDbName = val elif arg == '--fpColName': details.fpColName = val elif arg == '--minPath': details.minPath = int(val) elif arg == '--maxPath': details.maxPath = int(val) elif arg == '--nBitsPerHash': details.bitsPerHash = int(val) elif arg == '--discrim': details.discrimHash = 1 elif arg == '--smilesName': details.smilesName = val elif arg == '--molPkl': details.molPklName = val elif arg == '--useSD': details.useSmiles = False details.useSD = True elif arg == '--idName': details.idName = val elif arg == '--maxMols': details.maxMols = int(val) elif arg == '--useMACCS': details.fingerprinter = MACCSkeys.GenMACCSKeys elif arg == '--keepTable': details.replaceTable = False # SCREENER: elif arg == '--smilesTable': details.smilesTableName = val elif arg == '--topN': details.doThreshold = 0 details.topN = int(val) elif arg == '--thresh': details.doThreshold = 1 details.screenThresh = float(val) elif arg == '--smiles': details.probeSmiles = val elif arg == '--dice': details.metric = DataStructs.DiceSimilarity elif arg == '--cosine': details.metric = DataStructs.CosineSimilarity # CLUSTERS: elif arg == '--SLINK': details.clusterAlgo = Murtagh.SLINK elif arg == '--CLINK': details.clusterAlgo = Murtagh.CLINK elif arg == '--UPGMA': details.clusterAlgo = Murtagh.UPGMA elif arg == '--actTable': details.actTableName = val elif arg == '--actName': details.actName = val elif arg == '-h': Usage() return details if __name__ == '__main__': message("This is FingerprintMols version %s\n\n" % (__VERSION_STRING)) details = ParseArgs() FingerprintsFromDetails(details)
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Fingerprints/FingerprintMols.py", "copies": "1", "size": "17861", "license": "bsd-3-clause", "hash": -1879890710035294000, "line_mean": 29.6890034364, "line_max": 92, "alpha_frac": 0.5855775153, "autogenerated": false, "ratio": 3.762586896987571, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4848164412287571, "avg_score": null, "num_lines": null }
""" utility functionality for molecular similarity includes a command line app for screening databases Sample Usage: python MolSimilarity.py -d data.gdb -t daylight_sig --idName="Mol_ID" \ --topN=100 --smiles='c1(C=O)ccc(Oc2ccccc2)cc1' --smilesTable=raw_dop_data \ --smilesName="structure" -o results.csv """ from rdkit import RDConfig from rdkit import DataStructs from rdkit import Chem from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbModule from rdkit.DataStructs.TopNContainer import TopNContainer import sys, types from rdkit.six.moves import cPickle from rdkit.Chem.Fingerprints import FingerprintMols, DbFpSupplier try: from rdkit.VLib.NodeLib.DbPickleSupplier import _lazyDataSeq as _dataSeq except ImportError: _dataSeq = None from rdkit import DataStructs _cvsVersion = "$Id$" idx1 = _cvsVersion.find(':') + 1 idx2 = _cvsVersion.rfind('$') __VERSION_STRING = "%s" % (_cvsVersion[idx1:idx2]) def _ConstructSQL(details, extraFields=''): fields = '%s.%s' % (details.tableName, details.idName) join = '' if details.smilesTableName: if details.smilesName: fields = fields + ',%s' % (details.smilesName) join = 'join %s smi on smi.%s=%s.%s' % (details.smilesTableName, details.idName, details.tableName, details.idName) if details.actTableName: if details.actName: fields = fields + ',%s' % (details.actName) join = join + 'join %s act on act.%s=%s.%s' % (details.actTableName, details.idName, details.tableName, details.idName) #data = conn.GetData(fields=fields,join=join) if extraFields: fields += ',' + extraFields cmd = 'select %s from %s %s' % (fields, details.tableName, join) return cmd def ScreenInDb(details, mol): try: probeFp = apply(FingerprintMols.FingerprintMol, (mol, ), details.__dict__) except Exception: import traceback FingerprintMols.error('Error: problems fingerprinting molecule.\n') traceback.print_exc() return [] if details.dbName and details.tableName: try: conn = DbConnect(details.dbName, details.tableName) if hasattr(details, 'dbUser'): conn.user = details.dbUser if hasattr(details, 'dbPassword'): conn.password = details.dbPassword except Exception: import traceback FingerprintMols.error('Error: Problems establishing connection to database: %s|%s\n' % (details.dbName, details.tableName)) traceback.print_exc() if details.metric not in (DataStructs.TanimotoSimilarity, DataStructs.DiceSimilarity, DataStructs.CosineSimilarity): data = GetFingerprints(details) res = ScreenFingerprints(details, data, mol) else: res = [] if details.metric == DataStructs.TanimotoSimilarity: func = 'rd_tanimoto' pkl = probeFp.ToBitString() elif details.metric == DataStructs.DiceSimilarity: func = 'rd_dice' pkl = probeFp.ToBitString() elif details.metric == DataStructs.CosineSimilarity: func = 'rd_cosine' pkl = probeFp.ToBitString() extraFields = "%s(%s,%s) as tani" % (func, DbModule.placeHolder, details.fpColName) cmd = _ConstructSQL(details, extraFields=extraFields) if details.doThreshold: # we need to do a subquery here: cmd = "select * from (%s) tmp where tani>%f" % (cmd, details.screenThresh) cmd += " order by tani desc" if not details.doThreshold and details.topN > 0: cmd += " limit %d" % details.topN curs = conn.GetCursor() curs.execute(cmd, (pkl, )) res = curs.fetchall() return res def GetFingerprints(details): """ returns an iterable sequence of fingerprints each fingerprint will have a _fieldsFromDb member whose first entry is the id. """ if details.dbName and details.tableName: try: conn = DbConnect(details.dbName, details.tableName) if hasattr(details, 'dbUser'): conn.user = details.dbUser if hasattr(details, 'dbPassword'): conn.password = details.dbPassword except Exception: import traceback FingerprintMols.error('Error: Problems establishing connection to database: %s|%s\n' % (details.dbName, details.tableName)) traceback.print_exc() cmd = _ConstructSQL(details, extraFields=details.fpColName) curs = conn.GetCursor() #curs.execute(cmd) #print 'CURSOR:',curs,curs.closed if _dataSeq: suppl = _dataSeq(curs, cmd, depickle=not details.noPickle, klass=DataStructs.ExplicitBitVect) _dataSeq._conn = conn else: suppl = DbFpSupplier.ForwardDbFpSupplier(data, fpColName=details.fpColName) elif details.inFileName: conn = None try: inF = open(details.inFileName, 'r') except IOError: import traceback FingerprintMols.error('Error: Problems reading from file %s\n' % (details.inFileName)) traceback.print_exc() suppl = [] done = 0 while not done: try: id, fp = cPickle.load(inF) except Exception: done = 1 else: fp._fieldsFromDb = [id] suppl.append(fp) else: suppl = None return suppl def ScreenFingerprints(details, data, mol=None, probeFp=None): """ Returns a list of results """ if probeFp is None: try: probeFp = apply(FingerprintMols.FingerprintMol, (mol, ), details.__dict__) except Exception: import traceback FingerprintMols.error('Error: problems fingerprinting molecule.\n') traceback.print_exc() return [] if not probeFp: return [] res = [] if not details.doThreshold and details.topN > 0: topN = TopNContainer(details.topN) else: topN = [] res = [] count = 0 for pt in data: fp1 = probeFp if not details.noPickle: if type(pt) in (types.TupleType, types.ListType): id, fp = pt else: fp = pt id = pt._fieldsFromDb[0] score = DataStructs.FingerprintSimilarity(fp1, fp, details.metric) else: id, pkl = pt score = details.metric(fp1, str(pkl)) if topN: topN.Insert(score, id) elif not details.doThreshold or \ (details.doThreshold and score>=details.screenThresh): res.append((id, score)) count += 1 if hasattr(details, 'stopAfter') and count >= details.stopAfter: break for score, id in topN: res.append((id, score)) return res def ScreenFromDetails(details, mol=None): """ Returns a list of results """ if not mol: if not details.probeMol: smi = details.probeSmiles try: mol = Chem.MolFromSmiles(smi) except Exception: import traceback FingerprintMols.error('Error: problems generating molecule for smiles: %s\n' % (smi)) traceback.print_exc() return else: mol = details.probeMol if not mol: return if details.outFileName: try: outF = open(details.outFileName, 'w+') except IOError: FingerprintMols.error("Error: could not open output file %s for writing\n" % (details.outFileName)) return None else: outF = None if not hasattr(details, 'useDbSimilarity') or not details.useDbSimilarity: data = GetFingerprints(details) res = ScreenFingerprints(details, data, mol) else: res = ScreenInDb(details, mol) if outF: for pt in res: outF.write(','.join([str(x) for x in pt])) outF.write('\n') return res _usageDoc = """ Usage: MolSimilarity.py [args] <fName> If <fName> is provided and no tableName is specified (see below), data will be read from the pickled file <fName>. This file should contain a series of pickled (id,fingerprint) tuples. NOTE: at the moment the user is responsible for ensuring that the fingerprint parameters given at run time (used to fingerprint the probe molecule) match those used to generate the input fingerprints. Command line arguments are: - --smiles=val: sets the SMILES for the input molecule. This is a required argument. - -d _dbName_: set the name of the database from which to pull input fingerprint information. - -t _tableName_: set the name of the database table from which to pull input fingerprint information - --smilesTable=val: sets the name of the database table which contains SMILES for the input fingerprints. If this information is provided along with smilesName (see below), the output file will contain SMILES data - --smilesName=val: sets the name of the SMILES column in the input database. Default is *SMILES*. - --topN=val: sets the number of results to return. Default is *10*. - --thresh=val: sets the similarity threshold. - --idName=val: sets the name of the id column in the input database. Default is *ID*. - -o _outFileName_: name of the output file (output will be a CSV file with one line for each of the output molecules - --dice: use the DICE similarity metric instead of Tanimoto - --cosine: use the cosine similarity metric instead of Tanimoto - --fpColName=val: name to use for the column which stores fingerprints (in pickled format) in the output db table. Default is *AutoFragmentFP* - --minPath=val: minimum path length to be included in fragment-based fingerprints. Default is *1*. - --maxPath=val: maximum path length to be included in fragment-based fingerprints. Default is *7*. - --nBitsPerHash: number of bits to be set in the output fingerprint for each fragment. Default is *4*. - --discrim: use of path-based discriminators to hash bits. Default is *false*. - -V: include valence information in the fingerprints Default is *false*. - -H: include Hs in the fingerprint Default is *false*. - --useMACCS: use the public MACCS keys to do the fingerprinting (instead of a daylight-type fingerprint) """ if __name__ == '__main__': FingerprintMols.message("This is MolSimilarity version %s\n\n" % (__VERSION_STRING)) FingerprintMols._usageDoc = _usageDoc details = FingerprintMols.ParseArgs() ScreenFromDetails(details)
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Fingerprints/MolSimilarity.py", "copies": "1", "size": "10616", "license": "bsd-3-clause", "hash": -5818794250270112000, "line_mean": 30.9759036145, "line_max": 99, "alpha_frac": 0.6589110776, "autogenerated": false, "ratio": 3.641852487135506, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9712496407467367, "avg_score": 0.01765343145362771, "num_lines": 332 }
""" """ from __future__ import print_function import copy import random import numpy from rdkit.DataStructs.VectCollection import VectCollection from rdkit.ML import InfoTheory from rdkit.ML.DecTree import SigTree try: from rdkit.ML.FeatureSelect import CMIM except ImportError: CMIM = None def _GenerateRandomEnsemble(nToInclude, nBits): """ Generates a random subset of a group of indices **Arguments** - nToInclude: the size of the desired set - nBits: the maximum index to be included in the set **Returns** a list of indices """ # Before Python 2.3 added the random.sample() function, this was # way more complicated: return random.sample(range(nBits), nToInclude) def BuildSigTree(examples, nPossibleRes, ensemble=None, random=0, metric=InfoTheory.InfoType.BIASENTROPY, biasList=[1], depth=0, maxDepth=-1, useCMIM=0, allowCollections=False, verbose=0, **kwargs): """ **Arguments** - examples: the examples to be classified. Each example should be a sequence at least three entries long, with entry 0 being a label, entry 1 a BitVector and entry -1 an activity value - nPossibleRes: the number of result codes possible - ensemble: (optional) if this argument is provided, it should be a sequence which is used to limit the bits which are actually considered as potential descriptors. The default is None (use all bits). - random: (optional) If this argument is nonzero, it specifies the number of bits to be randomly selected for consideration at this node (i.e. this toggles the growth of Random Trees). The default is 0 (no random descriptor selection) - metric: (optional) This is an _InfoTheory.InfoType_ and sets the metric used to rank the bits. The default is _InfoTheory.InfoType.BIASENTROPY_ - biasList: (optional) If provided, this provides a bias list for the bit ranker. See the _InfoTheory.InfoBitRanker_ docs for an explanation of bias. The default value is [1], which biases towards actives. - maxDepth: (optional) the maximum depth to which the tree will be grown The default is -1 (no depth limit). - useCMIM: (optional) if this is >0, the CMIM algorithm (conditional mutual information maximization) will be used to select the descriptors used to build the trees. The value of the variable should be set to the number of descriptors to be used. This option and the ensemble option are mutually exclusive (CMIM will not be used if the ensemble is set), but it happily coexsts with the random argument (to only consider random subsets of the top N CMIM bits) The default is 0 (do not use CMIM) - depth: (optional) the current depth in the tree This is used in the recursion and should not be set by the client. **Returns** a SigTree.SigTreeNode with the root of the decision tree """ if verbose: print(' ' * depth, 'Build') tree = SigTree.SigTreeNode(None, 'node', level=depth) tree.SetData(-666) # tree.SetExamples(examples) # counts of each result code: # resCodes = map(lambda x:int(x[-1]),examples) resCodes = [int(x[-1]) for x in examples] # print('resCodes:',resCodes) counts = [0] * nPossibleRes for res in resCodes: counts[res] += 1 # print(' '*depth,'counts:',counts) nzCounts = numpy.nonzero(counts)[0] if verbose: print(' ' * depth, '\tcounts:', counts) if len(nzCounts) == 1: # bottomed out because there is only one result code left # with any counts (i.e. there's only one type of example # left... this is GOOD!). res = nzCounts[0] tree.SetLabel(res) tree.SetName(str(res)) tree.SetTerminal(1) elif maxDepth >= 0 and depth > maxDepth: # Bottomed out: max depth hit # We don't really know what to do here, so # use the heuristic of picking the most prevalent # result v = numpy.argmax(counts) tree.SetLabel(v) tree.SetName('%d?' % v) tree.SetTerminal(1) else: # find the variable which gives us the best improvement # We do this with an InfoBitRanker: fp = examples[0][1] nBits = fp.GetNumBits() ranker = InfoTheory.InfoBitRanker(nBits, nPossibleRes, metric) if biasList: ranker.SetBiasList(biasList) if CMIM is not None and useCMIM > 0 and not ensemble: ensemble = CMIM.SelectFeatures(examples, useCMIM, bvCol=1) if random: if ensemble: if len(ensemble) > random: picks = _GenerateRandomEnsemble(random, len(ensemble)) availBits = list(numpy.take(ensemble, picks)) else: availBits = list(range(len(ensemble))) else: availBits = _GenerateRandomEnsemble(random, nBits) else: availBits = None if availBits: ranker.SetMaskBits(availBits) # print(' 2:'*depth,availBits) useCollections = isinstance(examples[0][1], VectCollection) for example in examples: # print(' '*depth,example[1].ToBitString(),example[-1]) if not useCollections: ranker.AccumulateVotes(example[1], example[-1]) else: example[1].Reset() ranker.AccumulateVotes(example[1].orVect, example[-1]) try: bitInfo = ranker.GetTopN(1)[0] best = int(bitInfo[0]) gain = bitInfo[1] except Exception: import traceback traceback.print_exc() print('get top n failed') gain = -1.0 if gain <= 0.0: v = numpy.argmax(counts) tree.SetLabel(v) tree.SetName('?%d?' % v) tree.SetTerminal(1) return tree best = int(bitInfo[0]) # print(' '*depth,'\tbest:',bitInfo) if verbose: print(' ' * depth, '\tbest:', bitInfo) # set some info at this node tree.SetName('Bit-%d' % (best)) tree.SetLabel(best) # tree.SetExamples(examples) tree.SetTerminal(0) # loop over possible values of the new variable and # build a subtree for each one onExamples = [] offExamples = [] for example in examples: if example[1][best]: if allowCollections and useCollections: sig = copy.copy(example[1]) sig.DetachVectsNotMatchingBit(best) ex = [example[0], sig] if len(example) > 2: ex.extend(example[2:]) example = ex onExamples.append(example) else: offExamples.append(example) # print(' '*depth,len(offExamples),len(onExamples)) for ex in (offExamples, onExamples): if len(ex) == 0: v = numpy.argmax(counts) tree.AddChild('%d??' % v, label=v, data=0.0, isTerminal=1) else: child = BuildSigTree(ex, nPossibleRes, random=random, ensemble=ensemble, metric=metric, biasList=biasList, depth=depth + 1, maxDepth=maxDepth, verbose=verbose) if child is None: v = numpy.argmax(counts) tree.AddChild('%d???' % v, label=v, data=0.0, isTerminal=1) else: tree.AddChildNode(child) return tree def SigTreeBuilder(examples, attrs, nPossibleVals, initialVar=None, ensemble=None, randomDescriptors=0, **kwargs): nRes = nPossibleVals[-1] return BuildSigTree(examples, nRes, random=randomDescriptors, **kwargs)
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/DecTree/BuildSigTree.py", "copies": "4", "size": "7570", "license": "bsd-3-clause", "hash": 7574152487346788000, "line_mean": 31.6293103448, "line_max": 100, "alpha_frac": 0.6389696169, "autogenerated": false, "ratio": 3.680116674769081, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.011142782735495446, "num_lines": 232 }
""" command line utility for working with FragmentCatalogs (CASE-type analysis) **Usage** BuildFragmentCatalog [optional args] <filename> filename, the name of a delimited text file containing InData, is required for some modes of operation (see below) **Command Line Arguments** - -n *maxNumMols*: specify the maximum number of molecules to be processed - -b: build the catalog and OnBitLists *requires InData* - -s: score compounds *requires InData and a Catalog, can use OnBitLists* - -g: calculate info gains *requires Scores* - -d: show details about high-ranking fragments *requires a Catalog and Gains* - --catalog=*filename*: filename with the pickled catalog. If -b is provided, this file will be overwritten. - --onbits=*filename*: filename to hold the pickled OnBitLists. If -b is provided, this file will be overwritten - --scores=*filename*: filename to hold the text score data. If -s is provided, this file will be overwritten - --gains=*filename*: filename to hold the text gains data. If -g is provided, this file will be overwritten - --details=*filename*: filename to hold the text details data. If -d is provided, this file will be overwritten. - --minPath=2: specify the minimum length for a path - --maxPath=6: specify the maximum length for a path - --smiCol=1: specify which column in the input data file contains SMILES - --actCol=-1: specify which column in the input data file contains activities - --nActs=2: specify the number of possible activity values - --nBits=-1: specify the maximum number of bits to show details for """ from __future__ import print_function import sys,os from rdkit.six.moves import cPickle #@UnresolvedImport #pylint: disable=F0401 from rdkit.six import next from rdkit import Chem from rdkit import RDConfig from rdkit.Chem import FragmentCatalog from rdkit.Dbase.DbConnection import DbConnect import numpy from rdkit.ML import InfoTheory import types _cvsVersion="$Revision$" idx1 = _cvsVersion.find(':')+1 idx2 = _cvsVersion.rfind('$') __VERSION_STRING="%s"%(_cvsVersion[idx1:idx2]) def message(msg,dest=sys.stdout): dest.write(msg) def BuildCatalog(suppl,maxPts=-1,groupFileName=None, minPath=2,maxPath=6,reportFreq=10): """ builds a fragment catalog from a set of molecules in a delimited text block **Arguments** - suppl: a mol supplier - maxPts: (optional) if provided, this will set an upper bound on the number of points to be considered - groupFileName: (optional) name of the file containing functional group information - minPath, maxPath: (optional) names of the minimum and maximum path lengths to be considered - reportFreq: (optional) how often to display status information **Returns** a FragmentCatalog """ if groupFileName is None: groupFileName = os.path.join(RDConfig.RDDataDir,"FunctionalGroups.txt") fpParams = FragmentCatalog.FragCatParams(minPath,maxPath,groupFileName) catalog = FragmentCatalog.FragCatalog(fpParams) fgen = FragmentCatalog.FragCatGenerator() if maxPts >0: nPts = maxPts else: if hasattr(suppl,'__len__'): nPts = len(suppl) else: nPts = -1 for i,mol in enumerate(suppl): if i == nPts: break if i and not i%reportFreq: if nPts>-1: message('Done %d of %d, %d paths\n'%(i,nPts,catalog.GetFPLength())) else: message('Done %d, %d paths\n'%(i,catalog.GetFPLength())) fgen.AddFragsFromMol(mol,catalog) return catalog def ScoreMolecules(suppl,catalog,maxPts=-1,actName='',acts=None, nActs=2,reportFreq=10): """ scores the compounds in a supplier using a catalog **Arguments** - suppl: a mol supplier - catalog: the FragmentCatalog - maxPts: (optional) the maximum number of molecules to be considered - actName: (optional) the name of the molecule's activity property. If this is not provided, the molecule's last property will be used. - acts: (optional) a sequence of activity values (integers). If not provided, the activities will be read from the molecules. - nActs: (optional) number of possible activity values - reportFreq: (optional) how often to display status information **Returns** a 2-tuple: 1) the results table (a 3D array of ints nBits x 2 x nActs) 2) a list containing the on bit lists for each molecule """ nBits = catalog.GetFPLength() resTbl = numpy.zeros((nBits,2,nActs),numpy.int) obls = [] if not actName and not acts: actName = suppl[0].GetPropNames()[-1] fpgen = FragmentCatalog.FragFPGenerator() suppl.reset() i = 1 for mol in suppl: if i and not i%reportFreq: message('Done %d.\n'%(i)) if mol: if not acts: act = int(mol.GetProp(actName)) else: act = acts[i-1] fp = fpgen.GetFPForMol(mol,catalog) obls.append([x for x in fp.GetOnBits()]) for j in range(nBits): resTbl[j,0,act] += 1 for id in obls[i-1]: resTbl[id-1,0,act] -= 1 resTbl[id-1,1,act] += 1 else: obls.append([]) i+=1 return resTbl,obls def ScoreFromLists(bitLists,suppl,catalog,maxPts=-1,actName='',acts=None, nActs=2,reportFreq=10): """ similar to _ScoreMolecules()_, but uses pre-calculated bit lists for the molecules (this speeds things up a lot) **Arguments** - bitLists: sequence of on bit sequences for the input molecules - suppl: the input supplier (we read activities from here) - catalog: the FragmentCatalog - maxPts: (optional) the maximum number of molecules to be considered - actName: (optional) the name of the molecule's activity property. If this is not provided, the molecule's last property will be used. - nActs: (optional) number of possible activity values - reportFreq: (optional) how often to display status information **Returns** the results table (a 3D array of ints nBits x 2 x nActs) """ nBits = catalog.GetFPLength() if maxPts >0: nPts = maxPts else: nPts = len(bitLists) resTbl = numpy.zeros((nBits,2,nActs),numpy.int) if not actName and not acts: actName = suppl[0].GetPropNames()[-1] suppl.reset() for i in range(1,nPts+1): mol = next(suppl) if not acts: act = int(mol.GetProp(actName)) else: act = acts[i-1] if i and not i%reportFreq: message('Done %d of %d\n'%(i,nPts)) ids = set() for id in bitLists[i-1]: ids.add(id-1) for j in range(nBits): resTbl[j,0,act] += 1 for id in ids: resTbl[id,0,act] -= 1 resTbl[id,1,act] += 1 return resTbl def CalcGains(suppl,catalog,topN=-1,actName='',acts=None, nActs=2,reportFreq=10,biasList=None,collectFps=0): """ calculates info gains by constructing fingerprints *DOC* Returns a 2-tuple: 1) gains matrix 2) list of fingerprints """ nBits = catalog.GetFPLength() if topN < 0: topN = nBits if not actName and not acts: actName = suppl[0].GetPropNames()[-1] gains = [0]*nBits if hasattr(suppl,'__len__'): nMols = len(suppl) else: nMols = -1 fpgen = FragmentCatalog.FragFPGenerator() #ranker = InfoTheory.InfoBitRanker(nBits,nActs,InfoTheory.InfoType.ENTROPY) if biasList: ranker = InfoTheory.InfoBitRanker(nBits,nActs,InfoTheory.InfoType.BIASENTROPY) ranker.SetBiasList(biasList) else: ranker = InfoTheory.InfoBitRanker(nBits,nActs,InfoTheory.InfoType.ENTROPY) i = 0 fps = [] for mol in suppl: if not acts: try: act = int(mol.GetProp(actName)) except KeyError: message('ERROR: Molecule has no property: %s\n'%(actName)) message('\tAvailable properties are: %s\n'%(str(mol.GetPropNames()))) raise KeyError(actName) else: act = acts[i] if i and not i%reportFreq: if nMols>0: message('Done %d of %d.\n'%(i,nMols)) else: message('Done %d.\n'%(i)) fp = fpgen.GetFPForMol(mol,catalog) ranker.AccumulateVotes(fp,act) i+=1; if collectFps: fps.append(fp) gains = ranker.GetTopN(topN) return gains,fps def CalcGainsFromFps(suppl,fps,topN=-1,actName='',acts=None, nActs=2,reportFreq=10,biasList=None): """ calculates info gains from a set of fingerprints *DOC* """ nBits = len(fps[0]) if topN < 0: topN = nBits if not actName and not acts: actName = suppl[0].GetPropNames()[-1] gains = [0]*nBits if hasattr(suppl,'__len__'): nMols = len(suppl) else: nMols = -1 if biasList: ranker = InfoTheory.InfoBitRanker(nBits,nActs,InfoTheory.InfoType.BIASENTROPY) ranker.SetBiasList(biasList) else: ranker = InfoTheory.InfoBitRanker(nBits,nActs,InfoTheory.InfoType.ENTROPY) for i,mol in enumerate(suppl): if not acts: try: act = int(mol.GetProp(actName)) except KeyError: message('ERROR: Molecule has no property: %s\n'%(actName)) message('\tAvailable properties are: %s\n'%(str(mol.GetPropNames()))) raise KeyError(actName) else: act = acts[i] if i and not i%reportFreq: if nMols>0: message('Done %d of %d.\n'%(i,nMols)) else: message('Done %d.\n'%(i)) fp = fps[i] ranker.AccumulateVotes(fp,act) gains = ranker.GetTopN(topN) return gains def OutputGainsData(outF,gains,cat,nActs=2): actHeaders = ['Act-%d'%(x) for x in range(nActs)] if cat: outF.write('id,Description,Gain,%s\n'%(','.join(actHeaders))) else: outF.write('id,Gain,%s\n'%(','.join(actHeaders))) for entry in gains: id = int(entry[0]) outL = [str(id)] if cat: descr = cat.GetBitDescription(id) outL.append(descr) outL.append('%.6f'%entry[1]) outL += ['%d'%x for x in entry[2:]] outF.write(','.join(outL)) outF.write('\n') def ProcessGainsData(inF,delim=',',idCol=0,gainCol=1): """ reads a list of ids and info gains out of an input file """ res = [] inL = inF.readline() for line in inF.xreadlines(): splitL = line.strip().split(delim) res.append((splitL[idCol],float(splitL[gainCol]))) return res def ShowDetails(catalog,gains,nToDo=-1,outF=sys.stdout,idCol=0,gainCol=1, outDelim=','): """ gains should be a sequence of sequences. The idCol entry of each sub-sequence should be a catalog ID. _ProcessGainsData()_ provides suitable input. """ if nToDo < 0: nToDo = len(gains) for i in range(nToDo): id = int(gains[i][idCol]) gain = float(gains[i][gainCol]) descr = catalog.GetFragDescription(id) if descr: outF.write('%s\n'%(outDelim.join((str(id),descr,str(gain))))) def SupplierFromDetails(details): from rdkit.VLib.NodeLib.DbMolSupply import DbMolSupplyNode from rdkit.VLib.NodeLib.SmilesSupply import SmilesSupplyNode if details.dbName: conn = DbConnect(details.dbName,details.tableName) suppl = DbMolSupplyNode(conn.GetData()) else: suppl = SmilesSupplyNode(details.inFileName,delim=details.delim, nameColumn=details.nameCol, smilesColumn=details.smiCol, titleLine=details.hasTitle) if type(details.actCol)==types.IntType: suppl.reset() m = next(suppl) actName = m.GetPropNames()[details.actCol] details.actCol = actName if type(details.nameCol)==types.IntType: suppl.reset() m = next(suppl) nameName = m.GetPropNames()[details.nameCol] details.nameCol = nameName suppl.reset() if type(details.actCol)==types.IntType: suppl.reset() m = next(suppl) actName = m.GetPropNames()[details.actCol] details.actCol = actName if type(details.nameCol)==types.IntType: suppl.reset() m = next(suppl) nameName = m.GetPropNames()[details.nameCol] details.nameCol = nameName suppl.reset() return suppl def Usage(): print("This is BuildFragmentCatalog version %s"%(__VERSION_STRING)) print('usage error') #print(__doc__) sys.exit(-1) class RunDetails(object): numMols=-1 doBuild=0 doSigs=0 doScore=0 doGains=0 doDetails=0 catalogName=None onBitsName=None scoresName=None gainsName=None dbName='' tableName=None detailsName=None inFileName=None fpName=None minPath=2 maxPath=6 smiCol=1 actCol=-1 nameCol=-1 hasTitle=1 nActs = 2 nBits=-1 delim=',' biasList=None topN=-1 def ParseArgs(details): import getopt try: args,extras = getopt.getopt(sys.argv[1:],'n:d:cst', ['catalog=','onbits=', 'scoresFile=','gainsFile=','detailsFile=','fpFile=', 'minPath=','maxPath=','smiCol=','actCol=','nameCol=','nActs=', 'nBits=','biasList=','topN=', 'build','sigs','gains','details','score','noTitle']) except Exception: sys.stderr.write('Error parsing command line:\n') import traceback traceback.print_exc() Usage() for arg,val in args: if arg=='-n': details.numMols=int(val) elif arg=='-c': details.delim=',' elif arg=='-s': details.delim=' ' elif arg=='-t': details.delim='\t' elif arg=='-d': details.dbName=val elif arg=='--build': details.doBuild=1 elif arg=='--score': details.doScore=1 elif arg=='--gains': details.doGains=1 elif arg=='--sigs': details.doSigs=1 elif arg=='-details': details.doDetails=1 elif arg=='--catalog': details.catalogName=val elif arg=='--onbits': details.onBitsName=val elif arg=='--scoresFile': details.scoresName=val elif arg=='--gainsFile': details.gainsName=val elif arg=='--detailsFile': details.detailsName=val elif arg=='--fpFile': details.fpName=val elif arg=='--minPath': details.minPath=int(val) elif arg=='--maxPath': details.maxPath=int(val) elif arg=='--smiCol': try: details.smiCol=int(val) except ValueError: details.smiCol=val elif arg=='--actCol': try: details.actCol=int(val) except ValueError: details.actCol=val elif arg=='--nameCol': try: details.nameCol=int(val) except ValueError: details.nameCol=val elif arg=='--nActs': details.nActs=int(val) elif arg=='--nBits': details.nBits=int(val) elif arg=='--noTitle': details.hasTitle=0 elif arg=='--biasList': details.biasList=tuple(eval(val)) elif arg=='--topN': details.topN=int(val) elif arg=='-h': Usage() sys.exit(0) else: Usage() if len(extras): if details.dbName: details.tableName=extras[0] else: details.inFileName = extras[0] else: Usage() if __name__=='__main__': import time details = RunDetails() ParseArgs(details) from io import StringIO suppl = SupplierFromDetails(details) cat = None obls = None if details.doBuild: if not suppl: message("We require inData to generate a catalog\n") sys.exit(-2) message("Building catalog\n") t1 = time.time() cat = BuildCatalog(suppl,maxPts=details.numMols, minPath=details.minPath,maxPath=details.maxPath) t2 = time.time() message("\tThat took %.2f seconds.\n"%(t2-t1)) if details.catalogName: message("Dumping catalog data\n") cPickle.dump(cat,open(details.catalogName,'wb+')) elif details.catalogName: message("Loading catalog\n") cat = cPickle.load(open(details.catalogName,'rb')) if details.onBitsName: try: obls = cPickle.load(open(details.onBitsName,'rb')) except Exception: obls = None else: if len(obls)<(inD.count('\n')-1): obls = None scores = None if details.doScore: if not suppl: message("We require inData to score molecules\n") sys.exit(-2) if not cat: message("We require a catalog to score molecules\n") sys.exit(-2) message("Scoring compounds\n") if not obls or len(obls)<details.numMols: scores,obls = ScoreMolecules(suppl,cat,maxPts=details.numMols, actName=details.actCol, nActs=details.nActs) if details.scoresName: cPickle.dump(scores,open(details.scoresName,'wb+')) if details.onBitsName: cPickle.dump(obls,open(details.onBitsName,'wb+')) else: scores = ScoreFromLists(obls,suppl,cat,maxPts=details.numMols, actName=details.actCol, nActs=details.nActs) elif details.scoresName: scores = cPickle.load(open(details.scoresName,'rb')) if details.fpName and os.path.exists(details.fpName) and not details.doSigs: message("Reading fingerprints from file.\n") fps = cPickle.load(open(details.fpName,'rb')) else: fps = [] gains = None if details.doGains: if not suppl: message("We require inData to calculate gains\n") sys.exit(-2) if not (cat or fps): message("We require either a catalog or fingerprints to calculate gains\n") sys.exit(-2) message("Calculating Gains\n") t1 = time.time() if details.fpName: collectFps=1 else: collectFps=0 if not fps: gains,fps = CalcGains(suppl,cat,topN=details.topN,actName=details.actCol, nActs=details.nActs,biasList=details.biasList, collectFps=collectFps) if details.fpName: message("Writing fingerprint file.\n") tmpF=open(details.fpName,'wb+') cPickle.dump(fps,tmpF,1) tmpF.close() else: gains = CalcGainsFromFps(suppl,fps,topN=details.topN,actName=details.actCol, nActs=details.nActs,biasList=details.biasList) t2=time.time() message("\tThat took %.2f seconds.\n"%(t2-t1)) if details.gainsName: outF = open(details.gainsName,'w+') OutputGainsData(outF,gains,cat,nActs=details.nActs) else: if details.gainsName: inF = open(details.gainsName,'r') gains = ProcessGainsData(inF) if details.doDetails: if not cat: message("We require a catalog to get details\n") sys.exit(-2) if not gains: message("We require gains data to get details\n") sys.exit(-2) io = StringIO() io.write('id,SMILES,gain\n') ShowDetails(cat,gains,nToDo=details.nBits,outF=io) if details.detailsName: open(details.detailsName,'w+').write(io.getvalue()) else: sys.stderr.write(io.getvalue())
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/BuildFragmentCatalog.py", "copies": "1", "size": "19243", "license": "bsd-3-clause", "hash": -1612010710715912700, "line_mean": 27.8068862275, "line_max": 95, "alpha_frac": 0.6305669594, "autogenerated": false, "ratio": 3.328662861096696, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.927389636719158, "avg_score": 0.037066690661023353, "num_lines": 668 }
""" contains factory class for producing signatures """ from __future__ import print_function, division from rdkit.DataStructs import SparseBitVect,IntSparseIntVect,LongSparseIntVect from rdkit.Chem.Pharm2D import Utils import copy import numpy _verbose = False class SigFactory(object): """ SigFactory's are used by creating one, setting the relevant parameters, then calling the GetSignature() method each time a signature is required. """ def __init__(self,featFactory,useCounts=False,minPointCount=2,maxPointCount=3, shortestPathsOnly=True,includeBondOrder=False,skipFeats=None, trianglePruneBins=True): self.featFactory = featFactory self.useCounts=useCounts self.minPointCount=minPointCount self.maxPointCount=maxPointCount self.shortestPathsOnly=shortestPathsOnly self.includeBondOrder=includeBondOrder self.trianglePruneBins=trianglePruneBins if skipFeats is None: self.skipFeats=[] else: self.skipFeats=skipFeats self._bins = None self.sigKlass=None def SetBins(self,bins): """ bins should be a list of 2-tuples """ self._bins = copy.copy(bins) self.Init() def GetBins(self): return self._bins def GetNumBins(self): return len(self._bins) def GetSignature(self): return self.sigKlass(self._sigSize) def _GetBitSummaryData(self,bitIdx): nPts,combo,scaffold = self.GetBitInfo(bitIdx) fams=self.GetFeatFamilies() labels = [fams[x] for x in combo] dMat = numpy.zeros((nPts,nPts),numpy.int) dVect = Utils.nPointDistDict[nPts] for idx in range(len(dVect)): i,j = dVect[idx] dMat[i,j] = scaffold[idx] dMat[j,i] = scaffold[idx] return nPts,combo,scaffold,labels,dMat def GetBitDescriptionAsText(self,bitIdx,includeBins=0,fullPage=1): """ returns text with a description of the bit **Arguments** - bitIdx: an integer bit index - includeBins: (optional) if nonzero, information about the bins will be included as well - fullPage: (optional) if nonzero, html headers and footers will be included (so as to make the output a complete page) **Returns** a string with the HTML """ nPts,combo,scaffold,labels,dMat=self._GetBitSummaryData(bitIdx) def GetBitDescription(self,bitIdx): """ returns a text description of the bit **Arguments** - bitIdx: an integer bit index **Returns** a string """ nPts,combo,scaffold,labels,dMat=self._GetBitSummaryData(bitIdx) res = " ".join(labels)+ " " for row in dMat: res += "|"+" ".join([str(x) for x in row]) res += "|" return res def _findBinIdx(self,dists,bins,scaffolds): """ OBSOLETE: this has been rewritten in C++ Internal use only Returns the index of a bin defined by a set of distances. **Arguments** - dists: a sequence of distances (not binned) - bins: a sorted sequence of distance bins (2-tuples) - scaffolds: a list of possible scaffolds (bin combinations) **Returns** an integer bin index **Note** the value returned here is not an index in the overall signature. It is, rather, an offset of a scaffold in the possible combinations of distance bins for a given proto-pharmacophore. """ nBins = len(bins) nDists = len(dists) whichBins = [0]*nDists # This would be a ton easier if we had contiguous bins # i.e. if we could maintain the bins as a list of bounds) # because then we could use Python's bisect module. # Since we can't do that, we've got to do our own binary # search here. for i in range(nDists): dist = dists[i] where = -1 # do a simple binary search: startP,endP = 0,len(bins) while startP<endP: midP = (startP+endP) // 2 begBin,endBin = bins[midP] if dist < begBin: endP = midP elif dist >= endBin: startP = midP+1 else: where = midP break if where < 0: return None whichBins[i] = where res = scaffolds.index(tuple(whichBins)) if _verbose: print('----- _fBI -----------') print(' scaffolds:',scaffolds) print(' bins:',whichBins) print(' res:',res) return res def GetFeatFamilies(self): fams = [fam for fam in self.featFactory.GetFeatureFamilies() if fam not in self.skipFeats] fams.sort() return fams def GetMolFeats(self,mol): featFamilies=self.GetFeatFamilies() featMatches = {} for fam in featFamilies: featMatches[fam] = [] feats = self.featFactory.GetFeaturesForMol(mol,includeOnly=fam) for feat in feats: featMatches[fam].append(feat.GetAtomIds()) return [featMatches[x] for x in featFamilies] def GetBitIdx(self,featIndices,dists,sortIndices=True): """ returns the index for a pharmacophore described using a set of feature indices and distances **Arguments*** - featIndices: a sequence of feature indices - dists: a sequence of distance between the features, only the unique distances should be included, and they should be in the order defined in Utils. - sortIndices : sort the indices **Returns** the integer bit index """ nPoints = len(featIndices) if nPoints>3: raise NotImplementedError('>3 points not supported') if nPoints < self.minPointCount: raise IndexError('bad number of points') if nPoints > self.maxPointCount: raise IndexError('bad number of points') # this is the start of the nPoint-point pharmacophores startIdx = self._starts[nPoints] # # now we need to map the pattern indices to an offset from startIdx # if sortIndices: tmp = list(featIndices) tmp.sort() featIndices = tmp if featIndices[0]<0: raise IndexError('bad feature index') if max(featIndices)>=self._nFeats: raise IndexError('bad feature index') if nPoints==3: featIndices,dists=Utils.OrderTriangle(featIndices,dists) offset = Utils.CountUpTo(self._nFeats,nPoints,featIndices) if _verbose: print('offset for feature %s: %d'%(str(featIndices),offset)) offset *= len(self._scaffolds[len(dists)]) try: if _verbose: print('>>>>>>>>>>>>>>>>>>>>>>>') print('\tScaffolds:',repr(self._scaffolds[len(dists)]),type(self._scaffolds[len(dists)])) print('\tDists:',repr(dists),type(dists)) print('\tbins:',repr(self._bins),type(self._bins)) bin = self._findBinIdx(dists,self._bins,self._scaffolds[len(dists)]) except ValueError: fams = self.GetFeatFamilies() fams = [fams[x] for x in featIndices] raise IndexError('distance bin not found: feats: %s; dists=%s; bins=%s; scaffolds: %s'%(fams,dists,self._bins,self._scaffolds)) return startIdx + offset + bin def GetBitInfo(self,idx): """ returns information about the given bit **Arguments** - idx: the bit index to be considered **Returns** a 3-tuple: 1) the number of points in the pharmacophore 2) the proto-pharmacophore (tuple of pattern indices) 3) the scaffold (tuple of distance indices) """ if idx >= self._sigSize: raise IndexError('bad index (%d) queried. %d is the max'%(idx,self._sigSize)) # first figure out how many points are in the p'cophore nPts = self.minPointCount while nPts < self.maxPointCount and self._starts[nPts+1]<=idx: nPts+=1 # how far are we in from the start point? offsetFromStart = idx - self._starts[nPts] if _verbose: print('\t %d Points, %d offset'%(nPts,offsetFromStart)) # lookup the number of scaffolds nDists = len(Utils.nPointDistDict[nPts]) scaffolds = self._scaffolds[nDists] nScaffolds = len(scaffolds) # figure out to which proto-pharmacophore we belong: protoIdx = offsetFromStart // nScaffolds indexCombos = Utils.GetIndexCombinations(self._nFeats,nPts) combo = tuple(indexCombos[protoIdx]) if _verbose: print('\t combo: %s'%(str(combo))) # and which scaffold: scaffoldIdx = offsetFromStart % nScaffolds scaffold = scaffolds[scaffoldIdx] if _verbose: print('\t scaffold: %s'%(str(scaffold))) return nPts,combo,scaffold def Init(self): """ Initializes internal parameters. This **must** be called after making any changes to the signature parameters """ accum = 0 self._scaffolds = [0]*(len(Utils.nPointDistDict[self.maxPointCount+1])) self._starts = {} if not self.skipFeats: self._nFeats = len(self.featFactory.GetFeatureFamilies()) else: self._nFeats = 0 for fam in self.featFactory.GetFeatureFamilies(): if fam not in self.skipFeats: self._nFeats+=1 for i in range(self.minPointCount,self.maxPointCount+1): self._starts[i] = accum nDistsHere = len(Utils.nPointDistDict[i]) scaffoldsHere = Utils.GetPossibleScaffolds(i,self._bins, useTriangleInequality=self.trianglePruneBins) nBitsHere = len(scaffoldsHere) self._scaffolds[nDistsHere] = scaffoldsHere pointsHere = Utils.NumCombinations(self._nFeats,i) * nBitsHere accum += pointsHere self._sigSize = accum if not self.useCounts: self.sigKlass = SparseBitVect elif self._sigSize<2**31: self.sigKlass = IntSparseIntVect else: self.sigKlass = LongSparseIntVect def GetSigSize(self): return self._sigSize try: from rdkit.Chem.Pharmacophores import cUtils except ImportError: pass else: SigFactory._findBinIdx = cUtils.FindBinIdx
{ "repo_name": "adalke/rdkit", "path": "rdkit/Chem/Pharm2D/SigFactory.py", "copies": "4", "size": "10111", "license": "bsd-3-clause", "hash": -5578234675312812000, "line_mean": 28.3924418605, "line_max": 133, "alpha_frac": 0.6512708931, "autogenerated": false, "ratio": 3.551457674745346, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.021990167574008276, "num_lines": 344 }
""" contains factory class for producing signatures """ from __future__ import print_function, division from rdkit.DataStructs import SparseBitVect, IntSparseIntVect, LongSparseIntVect from rdkit.Chem.Pharm2D import Utils import copy import numpy _verbose = False class SigFactory(object): """ SigFactory's are used by creating one, setting the relevant parameters, then calling the GetSignature() method each time a signature is required. """ def __init__(self, featFactory, useCounts=False, minPointCount=2, maxPointCount=3, shortestPathsOnly=True, includeBondOrder=False, skipFeats=None, trianglePruneBins=True): self.featFactory = featFactory self.useCounts = useCounts self.minPointCount = minPointCount self.maxPointCount = maxPointCount self.shortestPathsOnly = shortestPathsOnly self.includeBondOrder = includeBondOrder self.trianglePruneBins = trianglePruneBins if skipFeats is None: self.skipFeats = [] else: self.skipFeats = skipFeats self._bins = None self.sigKlass = None def SetBins(self, bins): """ bins should be a list of 2-tuples """ self._bins = copy.copy(bins) self.Init() def GetBins(self): return self._bins def GetNumBins(self): return len(self._bins) def GetSignature(self): return self.sigKlass(self._sigSize) def _GetBitSummaryData(self, bitIdx): nPts, combo, scaffold = self.GetBitInfo(bitIdx) fams = self.GetFeatFamilies() labels = [fams[x] for x in combo] dMat = numpy.zeros((nPts, nPts), numpy.int) dVect = Utils.nPointDistDict[nPts] for idx in range(len(dVect)): i, j = dVect[idx] dMat[i, j] = scaffold[idx] dMat[j, i] = scaffold[idx] return nPts, combo, scaffold, labels, dMat def GetBitDescriptionAsText(self, bitIdx, includeBins=0, fullPage=1): """ returns text with a description of the bit **Arguments** - bitIdx: an integer bit index - includeBins: (optional) if nonzero, information about the bins will be included as well - fullPage: (optional) if nonzero, html headers and footers will be included (so as to make the output a complete page) **Returns** a string with the HTML """ nPts, combo, scaffold, labels, dMat = self._GetBitSummaryData(bitIdx) def GetBitDescription(self, bitIdx): """ returns a text description of the bit **Arguments** - bitIdx: an integer bit index **Returns** a string """ nPts, combo, scaffold, labels, dMat = self._GetBitSummaryData(bitIdx) res = " ".join(labels) + " " for row in dMat: res += "|" + " ".join([str(x) for x in row]) res += "|" return res def _findBinIdx(self, dists, bins, scaffolds): """ OBSOLETE: this has been rewritten in C++ Internal use only Returns the index of a bin defined by a set of distances. **Arguments** - dists: a sequence of distances (not binned) - bins: a sorted sequence of distance bins (2-tuples) - scaffolds: a list of possible scaffolds (bin combinations) **Returns** an integer bin index **Note** the value returned here is not an index in the overall signature. It is, rather, an offset of a scaffold in the possible combinations of distance bins for a given proto-pharmacophore. """ nBins = len(bins) nDists = len(dists) whichBins = [0] * nDists # This would be a ton easier if we had contiguous bins # i.e. if we could maintain the bins as a list of bounds) # because then we could use Python's bisect module. # Since we can't do that, we've got to do our own binary # search here. for i in range(nDists): dist = dists[i] where = -1 # do a simple binary search: startP, endP = 0, len(bins) while startP < endP: midP = (startP + endP) // 2 begBin, endBin = bins[midP] if dist < begBin: endP = midP elif dist >= endBin: startP = midP + 1 else: where = midP break if where < 0: return None whichBins[i] = where res = scaffolds.index(tuple(whichBins)) if _verbose: print('----- _fBI -----------') print(' scaffolds:', scaffolds) print(' bins:', whichBins) print(' res:', res) return res def GetFeatFamilies(self): fams = [fam for fam in self.featFactory.GetFeatureFamilies() if fam not in self.skipFeats] fams.sort() return fams def GetMolFeats(self, mol): featFamilies = self.GetFeatFamilies() featMatches = {} for fam in featFamilies: featMatches[fam] = [] feats = self.featFactory.GetFeaturesForMol(mol, includeOnly=fam) for feat in feats: featMatches[fam].append(feat.GetAtomIds()) return [featMatches[x] for x in featFamilies] def GetBitIdx(self, featIndices, dists, sortIndices=True): """ returns the index for a pharmacophore described using a set of feature indices and distances **Arguments*** - featIndices: a sequence of feature indices - dists: a sequence of distance between the features, only the unique distances should be included, and they should be in the order defined in Utils. - sortIndices : sort the indices **Returns** the integer bit index """ nPoints = len(featIndices) if nPoints > 3: raise NotImplementedError('>3 points not supported') if nPoints < self.minPointCount: raise IndexError('bad number of points') if nPoints > self.maxPointCount: raise IndexError('bad number of points') # this is the start of the nPoint-point pharmacophores startIdx = self._starts[nPoints] # # now we need to map the pattern indices to an offset from startIdx # if sortIndices: tmp = list(featIndices) tmp.sort() featIndices = tmp if featIndices[0] < 0: raise IndexError('bad feature index') if max(featIndices) >= self._nFeats: raise IndexError('bad feature index') if nPoints == 3: featIndices, dists = Utils.OrderTriangle(featIndices, dists) offset = Utils.CountUpTo(self._nFeats, nPoints, featIndices) if _verbose: print('offset for feature %s: %d' % (str(featIndices), offset)) offset *= len(self._scaffolds[len(dists)]) try: if _verbose: print('>>>>>>>>>>>>>>>>>>>>>>>') print('\tScaffolds:', repr(self._scaffolds[len(dists)]), type(self._scaffolds[len(dists)])) print('\tDists:', repr(dists), type(dists)) print('\tbins:', repr(self._bins), type(self._bins)) bin = self._findBinIdx(dists, self._bins, self._scaffolds[len(dists)]) except ValueError: fams = self.GetFeatFamilies() fams = [fams[x] for x in featIndices] raise IndexError('distance bin not found: feats: %s; dists=%s; bins=%s; scaffolds: %s' % (fams, dists, self._bins, self._scaffolds)) return startIdx + offset + bin def GetBitInfo(self, idx): """ returns information about the given bit **Arguments** - idx: the bit index to be considered **Returns** a 3-tuple: 1) the number of points in the pharmacophore 2) the proto-pharmacophore (tuple of pattern indices) 3) the scaffold (tuple of distance indices) """ if idx >= self._sigSize: raise IndexError('bad index (%d) queried. %d is the max' % (idx, self._sigSize)) # first figure out how many points are in the p'cophore nPts = self.minPointCount while nPts < self.maxPointCount and self._starts[nPts + 1] <= idx: nPts += 1 # how far are we in from the start point? offsetFromStart = idx - self._starts[nPts] if _verbose: print('\t %d Points, %d offset' % (nPts, offsetFromStart)) # lookup the number of scaffolds nDists = len(Utils.nPointDistDict[nPts]) scaffolds = self._scaffolds[nDists] nScaffolds = len(scaffolds) # figure out to which proto-pharmacophore we belong: protoIdx = offsetFromStart // nScaffolds indexCombos = Utils.GetIndexCombinations(self._nFeats, nPts) combo = tuple(indexCombos[protoIdx]) if _verbose: print('\t combo: %s' % (str(combo))) # and which scaffold: scaffoldIdx = offsetFromStart % nScaffolds scaffold = scaffolds[scaffoldIdx] if _verbose: print('\t scaffold: %s' % (str(scaffold))) return nPts, combo, scaffold def Init(self): """ Initializes internal parameters. This **must** be called after making any changes to the signature parameters """ accum = 0 self._scaffolds = [0] * (len(Utils.nPointDistDict[self.maxPointCount + 1])) self._starts = {} if not self.skipFeats: self._nFeats = len(self.featFactory.GetFeatureFamilies()) else: self._nFeats = 0 for fam in self.featFactory.GetFeatureFamilies(): if fam not in self.skipFeats: self._nFeats += 1 for i in range(self.minPointCount, self.maxPointCount + 1): self._starts[i] = accum nDistsHere = len(Utils.nPointDistDict[i]) scaffoldsHere = Utils.GetPossibleScaffolds(i, self._bins, useTriangleInequality=self.trianglePruneBins) nBitsHere = len(scaffoldsHere) self._scaffolds[nDistsHere] = scaffoldsHere pointsHere = Utils.NumCombinations(self._nFeats, i) * nBitsHere accum += pointsHere self._sigSize = accum if not self.useCounts: self.sigKlass = SparseBitVect elif self._sigSize < 2**31: self.sigKlass = IntSparseIntVect else: self.sigKlass = LongSparseIntVect def GetSigSize(self): return self._sigSize try: from rdkit.Chem.Pharmacophores import cUtils except ImportError: pass else: SigFactory._findBinIdx = cUtils.FindBinIdx
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Pharm2D/SigFactory.py", "copies": "1", "size": "10272", "license": "bsd-3-clause", "hash": 7061588894478114000, "line_mean": 28.4326647564, "line_max": 99, "alpha_frac": 0.6410630841, "autogenerated": false, "ratio": 3.584089323098395, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4725152407198395, "avg_score": null, "num_lines": null }
""" contains factory class for producing signatures """ from rdkit.DataStructs import SparseBitVect,IntSparseIntVect,LongSparseIntVect from rdkit.Chem.Pharm2D import Utils import copy import numpy _verbose = False class SigFactory(object): """ SigFactory's are used by creating one, setting the relevant parameters, then calling the GetSignature() method each time a signature is required. """ def __init__(self,featFactory,useCounts=False,minPointCount=2,maxPointCount=3, shortestPathsOnly=True,includeBondOrder=False,skipFeats=None, trianglePruneBins=True): self.featFactory = featFactory self.useCounts=useCounts self.minPointCount=minPointCount self.maxPointCount=maxPointCount self.shortestPathsOnly=shortestPathsOnly self.includeBondOrder=includeBondOrder self.trianglePruneBins=trianglePruneBins if skipFeats is None: self.skipFeats=[] else: self.skipFeats=skipFeats self._bins = None self.sigKlass=None def SetBins(self,bins): """ bins should be a list of 2-tuples """ self._bins = copy.copy(bins) self.Init() def GetBins(self): return self._bins def GetNumBins(self): return len(self._bins) def GetSignature(self): return self.sigKlass(self._sigSize) def _GetBitSummaryData(self,bitIdx): nPts,combo,scaffold = self.GetBitInfo(bitIdx) fams=self.GetFeatFamilies() labels = [fams[x] for x in combo] dMat = numpy.zeros((nPts,nPts),numpy.int) dVect = Utils.nPointDistDict[nPts] for idx in range(len(dVect)): i,j = dVect[idx] dMat[i,j] = scaffold[idx] dMat[j,i] = scaffold[idx] return nPts,combo,scaffold,labels,dMat def GetBitDescriptionAsText(self,bitIdx,includeBins=0,fullPage=1): """ returns text with a description of the bit **Arguments** - bitIdx: an integer bit index - includeBins: (optional) if nonzero, information about the bins will be included as well - fullPage: (optional) if nonzero, html headers and footers will be included (so as to make the output a complete page) **Returns** a string with the HTML """ nPts,combo,scaffold,labels,dMat=self._GetBitSummaryData(bitIdx) def GetBitDescription(self,bitIdx): """ returns a text description of the bit **Arguments** - bitIdx: an integer bit index **Returns** a string """ nPts,combo,scaffold,labels,dMat=self._GetBitSummaryData(bitIdx) res = " ".join(labels)+ " " for row in dMat: res += "|"+" ".join([str(x) for x in row]) res += "|" return res def _findBinIdx(self,dists,bins,scaffolds): """ OBSOLETE: this has been rewritten in C++ Internal use only Returns the index of a bin defined by a set of distances. **Arguments** - dists: a sequence of distances (not binned) - bins: a sorted sequence of distance bins (2-tuples) - scaffolds: a list of possible scaffolds (bin combinations) **Returns** an integer bin index **Note** the value returned here is not an index in the overall signature. It is, rather, an offset of a scaffold in the possible combinations of distance bins for a given proto-pharmacophore. """ nBins = len(bins) nDists = len(dists) whichBins = [0]*nDists # This would be a ton easier if we had contiguous bins # i.e. if we could maintain the bins as a list of bounds) # because then we could use Python's bisect module. # Since we can't do that, we've got to do our own binary # search here. for i in range(nDists): dist = dists[i] where = -1 # do a simple binary search: startP,endP = 0,len(bins) while startP<endP: midP = (startP+endP) // 2 begBin,endBin = bins[midP] if dist < begBin: endP = midP elif dist >= endBin: startP = midP+1 else: where = midP break if where < 0: return None whichBins[i] = where res = scaffolds.index(tuple(whichBins)) if _verbose: print '----- _fBI -----------' print ' scaffolds:',scaffolds print ' bins:',whichBins print ' res:',res return res def GetFeatFamilies(self): fams = [fam for fam in self.featFactory.GetFeatureFamilies() if fam not in self.skipFeats] fams.sort() return fams def GetMolFeats(self,mol): featFamilies=self.GetFeatFamilies() featMatches = {} for fam in featFamilies: featMatches[fam] = [] feats = self.featFactory.GetFeaturesForMol(mol,includeOnly=fam) for feat in feats: featMatches[fam].append(feat.GetAtomIds()) return [featMatches[x] for x in featFamilies] def GetBitIdx(self,featIndices,dists,sortIndices=True): """ returns the index for a pharmacophore described using a set of feature indices and distances **Arguments*** - featIndices: a sequence of feature indices - dists: a sequence of distance between the features, only the unique distances should be included, and they should be in the order defined in Utils. - sortIndices : sort the indices **Returns** the integer bit index """ nPoints = len(featIndices) if nPoints>3: raise NotImplementedError,'>3 points not supported' if nPoints < self.minPointCount: raise IndexError,'bad number of points' if nPoints > self.maxPointCount: raise IndexError,'bad number of points' # this is the start of the nPoint-point pharmacophores startIdx = self._starts[nPoints] # # now we need to map the pattern indices to an offset from startIdx # if sortIndices: tmp = list(featIndices) tmp.sort() featIndices = tmp if featIndices[0]<0: raise IndexError,'bad feature index' if max(featIndices)>=self._nFeats: raise IndexError,'bad feature index' if nPoints==3: featIndices,dists=Utils.OrderTriangle(featIndices,dists) offset = Utils.CountUpTo(self._nFeats,nPoints,featIndices) if _verbose: print 'offset for feature %s: %d'%(str(featIndices),offset) offset *= len(self._scaffolds[len(dists)]) try: if _verbose: print '>>>>>>>>>>>>>>>>>>>>>>>' print '\tScaffolds:',repr(self._scaffolds[len(dists)]),type(self._scaffolds[len(dists)]) print '\tDists:',repr(dists),type(dists) print '\tbins:',repr(self._bins),type(self._bins) bin = self._findBinIdx(dists,self._bins,self._scaffolds[len(dists)]) except ValueError: fams = self.GetFeatFamilies() fams = [fams[x] for x in featIndices] raise IndexError,'distance bin not found: feats: %s; dists=%s; bins=%s; scaffolds: %s'%(fams,dists,self._bins,self._scaffolds) return startIdx + offset + bin def GetBitInfo(self,idx): """ returns information about the given bit **Arguments** - idx: the bit index to be considered **Returns** a 3-tuple: 1) the number of points in the pharmacophore 2) the proto-pharmacophore (tuple of pattern indices) 3) the scaffold (tuple of distance indices) """ if idx >= self._sigSize: raise IndexError,'bad index (%d) queried. %d is the max'%(idx,self._sigSize) # first figure out how many points are in the p'cophore nPts = self.minPointCount while nPts < self.maxPointCount and self._starts[nPts+1]<=idx: nPts+=1 # how far are we in from the start point? offsetFromStart = idx - self._starts[nPts] if _verbose: print '\t %d Points, %d offset'%(nPts,offsetFromStart) # lookup the number of scaffolds nDists = len(Utils.nPointDistDict[nPts]) scaffolds = self._scaffolds[nDists] nScaffolds = len(scaffolds) # figure out to which proto-pharmacophore we belong: protoIdx = offsetFromStart / nScaffolds indexCombos = Utils.GetIndexCombinations(self._nFeats,nPts) combo = tuple(indexCombos[protoIdx]) if _verbose: print '\t combo: %s'%(str(combo)) # and which scaffold: scaffoldIdx = offsetFromStart % nScaffolds scaffold = scaffolds[scaffoldIdx] if _verbose: print '\t scaffold: %s'%(str(scaffold)) return nPts,combo,scaffold def Init(self): """ Initializes internal parameters. This **must** be called after making any changes to the signature parameters """ accum = 0 self._scaffolds = [0]*(len(Utils.nPointDistDict[self.maxPointCount+1])) self._starts = {} if not self.skipFeats: self._nFeats = len(self.featFactory.GetFeatureFamilies()) else: self._nFeats = 0 for fam in self.featFactory.GetFeatureFamilies(): if fam not in self.skipFeats: self._nFeats+=1 for i in range(self.minPointCount,self.maxPointCount+1): self._starts[i] = accum nDistsHere = len(Utils.nPointDistDict[i]) scaffoldsHere = Utils.GetPossibleScaffolds(i,self._bins, useTriangleInequality=self.trianglePruneBins) nBitsHere = len(scaffoldsHere) self._scaffolds[nDistsHere] = scaffoldsHere pointsHere = Utils.NumCombinations(self._nFeats,i) * nBitsHere accum += pointsHere self._sigSize = accum if not self.useCounts: self.sigKlass = SparseBitVect elif self._sigSize<2**31: self.sigKlass = IntSparseIntVect else: self.sigKlass = LongSparseIntVect def GetSigSize(self): return self._sigSize try: from rdkit.Chem.Pharmacophores import cUtils except ImportError: pass else: SigFactory._findBinIdx = cUtils.FindBinIdx
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Pharm2D/SigFactory.py", "copies": "2", "size": "10043", "license": "bsd-3-clause", "hash": 6364832570176836000, "line_mean": 28.2798833819, "line_max": 132, "alpha_frac": 0.6519964154, "autogenerated": false, "ratio": 3.543754410726888, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.02247394797974606, "num_lines": 343 }
""" Definitions for 2D Pharmacophores from: Gobbi and Poppinger, Biotech. Bioeng. _61_ 47-54 (1998) """ from rdkit import Chem from rdkit.Chem.Pharm2D.SigFactory import SigFactory from rdkit.Chem import ChemicalFeatures fdef = """ DefineFeature Hydrophobic [$([C;H2,H1](!=*)[C;H2,H1][C;H2,H1][$([C;H1,H2,H3]);!$(C=*)]),$(C([C;H2,H3])([C;H2,H3])[C;H2,H3])] Family LH Weights 1.0 EndFeature DefineFeature Donor [$([N;!H0;v3]),$([N;!H0;+1;v4]),$([O,S;H1;+0]),$([n;H1;+0])] Family HD Weights 1.0 EndFeature DefineFeature Acceptor [$([O,S;H1;v2]-[!$(*=[O,N,P,S])]),$([O,S;H0;v2]),$([O,S;-]),$([N&v3;H1,H2]-[!$(*=[O,N,P,S])]),$([N;v3;H0]),$([n,o,s;+0]),F] Family HA Weights 1.0 EndFeature DefineFeature AromaticAttachment [$([a;D3](@*)(@*)*)] Family AR Weights 1.0 EndFeature DefineFeature AliphaticAttachment [$([A;D3](@*)(@*)*)] Family RR Weights 1.0 EndFeature DefineFeature UnusualAtom [!#1;!#6;!#7;!#8;!#9;!#16;!#17;!#35;!#53] Family X Weights 1.0 EndFeature DefineFeature BasicGroup [$([N;H2&+0][$([C,a]);!$([C,a](=O))]),$([N;H1&+0]([$([C,a]);!$([C,a](=O))])[$([C,a]);!$([C,a](=O))]),$([N;H0&+0]([C;!$(C(=O))])([C;!$(C(=O))])[C;!$(C(=O))]),$([N,n;X2;+0])] Family BG Weights 1.0 EndFeature DefineFeature AcidicGroup [$([C,S](=[O,S,P])-[O;H1])] Family AG Weights 1.0 EndFeature """ defaultBins = [(2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 100)] def _init(): global labels, patts, factory featFactory = ChemicalFeatures.BuildFeatureFactoryFromString(fdef) factory = SigFactory(featFactory, minPointCount=2, maxPointCount=3) factory.SetBins(defaultBins) factory.Init() _init()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Pharm2D/Gobbi_Pharm2D.py", "copies": "1", "size": "1931", "license": "bsd-3-clause", "hash": -49881716686581150, "line_mean": 29.171875, "line_max": 197, "alpha_frac": 0.6105644744, "autogenerated": false, "ratio": 2.1819209039548024, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.32924853783548025, "avg_score": null, "num_lines": null }
from rdkit import Chem from rdfragcatalog import * import sys def message(msg,dest=sys.stdout): dest.write(msg) class BitGainsInfo(object): id=-1 description='' gain=0.0 nPerClass=None def ProcessGainsFile(fileName,nToDo=-1,delim=',',haveDescriptions=1): inFile = open(fileName,'r') nRead = 0 res = [] for line in inFile.xreadlines(): nRead += 1 splitL = [x.strip() for x in line.split(delim)] if nRead != 1 and len(splitL): bit = BitGainsInfo() bit.id = int(splitL[0]) col = 1 if haveDescriptions: bit.description = splitL[col] col += 1 bit.gain = float(splitL[col]) col += 1 nPerClass = [] for entry in splitL[col:]: nPerClass.append(int(entry)) bit.nPerClass = nPerClass res.append(bit) if len(res)==nToDo: break return res def BuildAdjacencyList(catalog,bits,limitInclusion=1,orderLevels=0): adjs = {} levels = {} bitIds = [bit.id for bit in bits] for bitId in bitIds: entry = catalog.GetBitEntryId(bitId) tmp = [] order = catalog.GetEntryOrder(entry) s = levels.get(order,set()) s.add(bitId) levels[order] = s for down in catalog.GetEntryDownIds(entry): id = catalog.GetEntryBitId(down) if not limitInclusion or id in bitIds: tmp.append(id) order = catalog.GetEntryOrder(down) s = levels.get(order,set()) s.add(id) levels[order] = s adjs[bitId] = tmp if orderLevels: # we'll play a little game and sort the indices in each level by # the number of downlinks they have: for order in levels.keys(): ids = levels[order] counts = [len(adjs[id]) for id in ids] countOrder = argsort(counts) l = [ids[x] for x in countOrder] l.reverse() levels[order] = l return adjs,levels def GetMolsMatchingBit(mols,bit,fps): res = [] if isinstance(bit,BitGainsInfo): bitId = bit.id else: bitId = bit for i,mol in enumerate(mols): fp = fps[i] if fp[bitId]: res.append(mol) return res
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/FragmentCatalog.py", "copies": "2", "size": "2388", "license": "bsd-3-clause", "hash": -2844270085012729000, "line_mean": 24.4042553191, "line_max": 69, "alpha_frac": 0.6264656616, "autogenerated": false, "ratio": 3.175531914893617, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48019975764936174, "avg_score": null, "num_lines": null }
""" functionality for finding pharmacophore matches in molecules See Docs/Chem/Pharm2D.triangles.jpg for an illustration of the way pharmacophores are broken into triangles and labelled. See Docs/Chem/Pharm2D.signatures.jpg for an illustration of bit numbering """ from rdkit import Chem from rdkit.Chem.Pharm2D import Utils import types import exceptions class MatchError(exceptions.Exception): pass _verbose = 0 def GetAtomsMatchingBit(sigFactory,bitIdx,mol,dMat=None,justOne=0,matchingAtoms=None): """ Returns a list of lists of atom indices for a bit **Arguments** - sigFactory: a SigFactory - bitIdx: the bit to be queried - mol: the molecule to be examined - dMat: (optional) the distance matrix of the molecule - justOne: (optional) if this is nonzero, only the first match will be returned. - matchingAtoms: (optional) if this is nonzero, it should contain a sequence of sequences with the indices of atoms in the molecule which match each of the patterns used by the signature. **Returns** a list of tuples with the matching atoms """ assert sigFactory.shortestPathsOnly,'not implemented for non-shortest path signatures' nPts,featCombo,scaffold = sigFactory.GetBitInfo(bitIdx) if _verbose: print 'info:',nPts print '\t',featCombo print '\t',scaffold if matchingAtoms is None: matchingAtoms = sigFactory.GetMolFeats(mol) # find the atoms that match each features fams = sigFactory.GetFeatFamilies() choices = [] for featIdx in featCombo: tmp = matchingAtoms[featIdx] if tmp: choices.append(tmp) else: # one of the patterns didn't find a match, we # can return now if _verbose: print 'no match found for feature:',featIdx return [] if _verbose: print 'choices:' print choices if dMat is None: dMat = Chem.GetDistanceMatrix(mol,sigFactory.includeBondOrder) matches = [] distsToCheck = Utils.nPointDistDict[nPts] protoPharmacophores = Utils.GetAllCombinations(choices,noDups=1) res = [] for protoPharm in protoPharmacophores: if _verbose: print 'protoPharm:',protoPharm for i in range(len(distsToCheck)): dLow,dHigh = sigFactory.GetBins()[scaffold[i]] a1,a2 = distsToCheck[i] # # FIX: this is making all kinds of assumptions about # things being single-atom matches (or at least that # only the first atom matters # idx1,idx2 = protoPharm[a1][0],protoPharm[a2][0] dist = dMat[idx1,idx2] if _verbose: print '\t dist: %d->%d = %d (%d,%d)'%(idx1,idx2,dist,dLow,dHigh) if dist < dLow or dist >= dHigh: break else: if _verbose: print 'Found one' # we found it protoPharm.sort() protoPharm = tuple(protoPharm) if protoPharm not in res: res.append(protoPharm) if justOne: break return res if __name__ == '__main__': from rdkit import Chem from rdkit.Chem.Pharm2D import SigFactory,Generate factory = SigFactory.SigFactory() factory.SetBins([(1,2),(2,5),(5,8)]) factory.SetPatternsFromSmarts(['O','N']) factory.SetMinCount(2) factory.SetMaxCount(3) sig = factory.GetSignature() mol = Chem.MolFromSmiles('OCC(=O)CCCN') Generate.Gen2DFingerprint(mol,sig) print 'onbits:',list(sig.GetOnBits()) _verbose=0 for bit in sig.GetOnBits(): atoms = GetAtomsMatchingBit(sig,bit,mol) print '\tBit %d: '%(bit),atoms print '--------------------------' sig = factory.GetSignature() sig.SetIncludeBondOrder(1) Generate.Gen2DFingerprint(mol,sig) print 'onbits:',list(sig.GetOnBits()) for bit in sig.GetOnBits(): atoms = GetAtomsMatchingBit(sig,bit,mol) print '\tBit %d: '%(bit),atoms
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/Pharm2D/Matcher.py", "copies": "2", "size": "4099", "license": "bsd-3-clause", "hash": -6898277712822001000, "line_mean": 26.6959459459, "line_max": 88, "alpha_frac": 0.6728470359, "autogenerated": false, "ratio": 3.404485049833887, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5077332085733888, "avg_score": null, "num_lines": null }
import sys from rdkit import Chem from rdkit.Chem.rdfragcatalog import * def message(msg, dest=sys.stdout): dest.write(msg) class BitGainsInfo(object): id = -1 description = '' gain = 0.0 nPerClass = None def ProcessGainsFile(fileName, nToDo=-1, delim=',', haveDescriptions=1): inFile = open(fileName, 'r') nRead = 0 res = [] for line in inFile.xreadlines(): nRead += 1 splitL = [x.strip() for x in line.split(delim)] if nRead != 1 and len(splitL): bit = BitGainsInfo() bit.id = int(splitL[0]) col = 1 if haveDescriptions: bit.description = splitL[col] col += 1 bit.gain = float(splitL[col]) col += 1 nPerClass = [] for entry in splitL[col:]: nPerClass.append(int(entry)) bit.nPerClass = nPerClass res.append(bit) if len(res) == nToDo: break return res def BuildAdjacencyList(catalog, bits, limitInclusion=1, orderLevels=0): adjs = {} levels = {} bitIds = [bit.id for bit in bits] for bitId in bitIds: entry = catalog.GetBitEntryId(bitId) tmp = [] order = catalog.GetEntryOrder(entry) s = levels.get(order, set()) s.add(bitId) levels[order] = s for down in catalog.GetEntryDownIds(entry): id = catalog.GetEntryBitId(down) if not limitInclusion or id in bitIds: tmp.append(id) order = catalog.GetEntryOrder(down) s = levels.get(order, set()) s.add(id) levels[order] = s adjs[bitId] = tmp if orderLevels: # we'll play a little game and sort the indices in each level by # the number of downlinks they have: for order in levels.keys(): ids = levels[order] counts = [len(adjs[id]) for id in ids] countOrder = argsort(counts) l = [ids[x] for x in countOrder] l.reverse() levels[order] = l return adjs, levels def GetMolsMatchingBit(mols, bit, fps): res = [] if isinstance(bit, BitGainsInfo): bitId = bit.id else: bitId = bit for i, mol in enumerate(mols): fp = fps[i] if fp[bitId]: res.append(mol) return res
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/FragmentCatalog.py", "copies": "12", "size": "2420", "license": "bsd-3-clause", "hash": 8292472122260891000, "line_mean": 23.9484536082, "line_max": 72, "alpha_frac": 0.6219008264, "autogenerated": false, "ratio": 3.1758530183727034, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.021880169004199396, "num_lines": 97 }