Python rdkit.Chem.Draw.MolsToGridImage() Examples

The following are 11 code examples of rdkit.Chem.Draw.MolsToGridImage(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rdkit.Chem.Draw , or try the search function .
Example #1
Source File: chem.py    From spektral with MIT License 8 votes vote down vote up
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 
Example #2
Source File: main.py    From REINVENT with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: Show_Epoch.py    From DeepFMPO with MIT License 6 votes vote down vote up
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() 
Example #4
Source File: generate.py    From graph-nvp with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: figure.py    From DrugEx with MIT License 6 votes vote down vote up
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)) 
Example #6
Source File: tensorboard.py    From reinvent-randomized with MIT License 5 votes vote down vote up
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) 
Example #7
Source File: app.py    From bootcamp with Apache License 2.0 5 votes vote down vote up
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 
Example #8
Source File: Show_Epoch.py    From DeepFMPO with MIT License 5 votes vote down vote up
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') 
Example #9
Source File: utils.py    From MolGAN with MIT License 5 votes vote down vote up
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)) 
Example #10
Source File: mol_distance.py    From ORGAN with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #11
Source File: tensorboard.py    From reinvent-scaffold-decorator with MIT License 5 votes vote down vote up
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)