本文整理汇总了Python中rdkit.Chem.Draw.MolsToGridImage方法的典型用法代码示例。如果您正苦于以下问题:Python Draw.MolsToGridImage方法的具体用法?Python Draw.MolsToGridImage怎么用?Python Draw.MolsToGridImage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdkit.Chem.Draw
的用法示例。
在下文中一共展示了Draw.MolsToGridImage方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def main(epoch):
decodings2 = read_decodings()
in_mols = np.load("History/in-{}.npy".format(epoch))
out_mols = np.load("History/out-{}.npy".format(epoch))
in_mols = [decode(m, decodings2) for m in in_mols]
out_mols = [safe_decode(m, decodings2) for m in out_mols]
use = [(not out_mols[i] is None) and \
Chem.MolToSmiles(out_mols[i]) != Chem.MolToSmiles(in_mols[i])
for i in range(len(out_mols))]
plot_mols = [[m1,m2] for m1,m2,u in zip(in_mols,out_mols,use) if u]
order = [np.sum(evaluate_chem_mol(out_mols[i])) for i in range(len(out_mols)) if use[i]]
plot_mols = [x for _,x in sorted(zip(order,plot_mols),reverse=True)]
plot_mols = [x for y in plot_mols for x in y ]
# #
plot = Draw.MolsToGridImage(plot_mols[:50], molsPerRow=2)
plot.show()
示例2: plot_rdkit_svg_grid
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def plot_rdkit_svg_grid(mols, mols_per_row=5, filename=None, **kwargs):
"""
Plots a grid of RDKit molecules in SVG.
:param mols: a list of RDKit molecules
:param mols_per_row: size of the grid
:param filename: save an image with the given filename
:param kwargs: additional arguments for `RDKit.Chem.Draw.MolsToGridImage`
:return: the SVG as a string
"""
if rdc is None:
raise ImportError('`draw_rdkit_mol` requires RDkit.')
svg = Draw.MolsToGridImage(mols, molsPerRow=mols_per_row, useSVG=True, **kwargs)
if filename is not None:
if not filename.endswith('.svg'):
filename += '.svg'
with open(filename, 'w') as f:
f.write(svg)
return svg
示例3: update
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def update():
score = np.load(os.path.join(path, "Scores.npy"))
with open(os.path.join(path, "SMILES"), "r") as f:
mols = []
scores = []
for line in f:
line = line.split()
mol = Chem.MolFromSmiles(line[0])
if mol and len(mols)<6:
mols.append(mol)
scores.append(line[1])
img = Draw.MolsToGridImage(mols, molsPerRow=3, legends=scores, subImgSize=(250,250), useSVG=True)
img = img.replace("FFFFFF", "EDEDED")
img_fig.text = '<h2>Generated Molecules</h2>' + '<div class="img_inside">' + img + '</div>'
score_source.data = dict(x=score[0], y=score[1], y_mean=running_average(score[1], 50))
for name, w in weights.items():
current_weights = np.load(os.path.join(path, name)).reshape(-1)
hist, edge = np.histogram(current_weights, density=True, bins=50)
w['hist_source'].data = dict(hist=hist, left_edge=edge[:-1], right_edge=edge[1:])
current_weights = downsample(current_weights, 50)
w['bar_source'].data = dict(x=range(len(current_weights)), y=current_weights)
示例4: visualize_interpolation
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def visualize_interpolation(filepath, model, mol_smiles=None, mols_per_row=13,
delta=0.1, seed=0, atomic_num_list=[6, 7, 8, 9, 0], true_data=None, gpu=-1):
z0 = None
if mol_smiles is not None:
z0 = get_latent_vec(model, mol_smiles)
else:
with chainer.no_backprop_mode():
np.random.seed(seed)
mol_index = np.random.randint(0, len(true_data))
adj = np.expand_dims(true_data[mol_index][1], axis=0)
x = np.expand_dims(true_data[mol_index][0], axis=0)
z0 = model(adj, x)
z0 = np.hstack((z0[0][0].data, z0[0][1].data)).squeeze(0)
adj, x = generate_mols_interpolation(model, z0=z0, mols_per_row=mols_per_row, delta=delta, seed=seed, gpu=gpu)
adj = _to_numpy_array(adj)
x = _to_numpy_array(x)
interpolation_mols = [valid_mol(construct_mol(x_elem, adj_elem, atomic_num_list))
for x_elem, adj_elem in zip(x, adj)]
valid_mols = [mol for mol in interpolation_mols if mol is not None]
print('interpolation_mols valid {} / {}'
.format(len(valid_mols), len(interpolation_mols)))
img = Draw.MolsToGridImage(interpolation_mols, molsPerRow=mols_per_row, subImgSize=(250, 250)) # , useSVG=True
img.save(filepath)
示例5: fig11
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def fig11():
""" Generated molecules exhibition based on probability score (X-axis) and
Tanimoto distance (Y-axis).
"""
dist = diversity('mol_e_10_1_500x10.txt', 'data/CHEMBL251.txt')
dist.to_csv('distance.txt', index=None, sep='\t')
df = pd.read_table('distance.txt')
dists = [0.3, 0.4, 0.5, 0.6, 0.7, 1.0]
scores = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
mols = []
for i, dist in enumerate(dists):
if i == len(dists) - 1: continue
samples = df[(df.DIST > dist) & (df.DIST < dists[i + 1])].sort_values("SCORE")
for j, score in enumerate(scores):
if j == len(scores) - 1: continue
sample = samples[(samples.SCORE > score) & (samples.SCORE < scores[j+1])]
if len(sample) > 0:
sample = sample.sample(1)
print(sample.values)
mols += [Chem.MolFromSmiles(smile) for smile in sample.CANONICAL_SMILES]
img = Draw.MolsToGridImage(mols, molsPerRow=5, subImgSize=(400, 300))
img.save('Figure_11_%f.tif' % (dist))
示例6: add_mols
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def add_mols(writer, tag, mols, mols_per_row=1, legends=None, global_step=None, walltime=None, size_per_mol=(300, 300)):
"""
Adds molecules in a grid.
"""
image = rkcd.MolsToGridImage(mols, molsPerRow=mols_per_row, subImgSize=size_per_mol, legends=legends)
add_image(writer, tag, image, global_step, walltime)
示例7: do_search_api
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def do_search_api():
args = reqparse.RequestParser(). \
add_argument("Table", type=str). \
add_argument("Num", type=int, default=1). \
add_argument("Molecular", type=str). \
parse_args()
table_name = args['Table']
if not table_name:
table_name = DEFAULT_TABLE
top_k = args['Num']
molecular_name = args['Molecular']
if not molecular_name:
return "no molecular"
if molecular_name:
try:
shutil.rmtree(UPLOAD_PATH)
os.mkdir(UPLOAD_PATH)
except:
print("cannot remove:", UPLOAD_PATH)
try:
res_smi, res_distance, ids= do_search(table_name, molecular_name, top_k)
except:
return "There has no results, please input the correct molecular and ensure the table has data."
res_mol = []
for i in range(len(res_smi)):
mol = Chem.MolFromSmiles(res_smi[i])
res_mol.append(mol)
print("res_mol:",len(res_mol))
re = {}
for i in range(len(res_smi)):
times = int(time.time())
sub_res_mol = [res_mol[i]]
sub_img = Draw.MolsToGridImage(sub_res_mol, molsPerRow=1, subImgSize=(500, 500))
sub_img.save(UPLOAD_PATH + "/similarities_results_" + str(ids[i]) + "_" + str(times) + ".png")
res_img = request.url_root + "data/similarities_results_"+ str(ids[i]) + "_" + str(times) +".png"
re[res_img] = [res_smi[i],res_distance[i]]
# img = Draw.MolsToGridImage(res_mol, molsPerRow=1, subImgSize=(500, 500),legends=["%s - %s" % (res_smi[x] , str(res_distance[x])) for x in range(len(res_mol))])
return jsonify(re), 200
return "not found", 400
示例8: main
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def main(epoch, savefile=None, imagefile=None):
decodings2 = read_decodings()
in_mols = np.load("History/in-{}.npy".format(epoch))
out_mols = np.load("History/out-{}.npy".format(epoch))
in_mols = [decode(m, decodings2) for m in in_mols]
out_mols = [safe_decode(m, decodings2) for m in out_mols]
use = [(not out_mols[i] is None) and \
Chem.MolToSmiles(out_mols[i]) != Chem.MolToSmiles(in_mols[i])
for i in range(len(out_mols))]
plot_mols = [[m1,m2] for m1,m2,u in zip(in_mols,out_mols,use) if u]
order = [np.sum(evaluate_chem_mol(out_mols[i])) for i in range(len(out_mols)) if use[i]]
plot_mols = [x for _,x in sorted(zip(order,plot_mols),key=lambda x:x[0],
reverse=True)]
plot_mols = [x for y in plot_mols for x in y ]
plot = Draw.MolsToGridImage(plot_mols[:50], molsPerRow=2)
if not imagefile is None:
plot.save(imagefile)
plot.show()
if not savefile is None:
with open(savefile, "w") as f:
f.write("Initial molecule ; Modified molecule\n")
for i in range(0,len(plot_mols), 2):
f.write(f'{Chem.MolToSmiles(plot_mols[i])} ; {Chem.MolToSmiles(plot_mols[i+1])}\n')
示例9: mols2grid_image
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def mols2grid_image(mols, molsPerRow):
mols = [e if e is not None else Chem.RWMol() for e in mols]
for mol in mols:
AllChem.Compute2DCoords(mol)
return Draw.MolsToGridImage(mols, molsPerRow=molsPerRow, subImgSize=(150, 150))
示例10: molgrid_image
# 需要导入模块: from rdkit.Chem import Draw [as 别名]
# 或者: from rdkit.Chem.Draw import MolsToGridImage [as 别名]
def molgrid_image(smiles, file_name, labels=None, molPerRow=5):
df = pd.DataFrame({'smiles': smiles})
PandasTools.AddMoleculeColumnToFrame(df, 'smiles', 'mol')
if labels is None:
labels = ['{:d}'.format(i) for i in df.index]
svg = Draw.MolsToGridImage(
df['mol'], molsPerRow=5, legends=labels, useSVG=True)
save_svg(svg, file_name + '.svg', dpi=150)
return