2
1

More than 1 year has passed since last update.

[ケモインフォマティクス] smilesから分子構造を描画してExcelに入れる。

Last updated at Posted at 2022-11-16

分子のデータをsmilesで管理することは多くあると思います。
一方、smilesは分子構造について他人に説明したいときや可読性についてはなかなか悪いため、構造が一目でわかる形で管理したいことはよくあるでしょう。

そこで、今回はsmilesのデータから構造を描画しExcelで管理する方法をまとめます。

ライブラリにはExcelを操作するopenpyxlと安定のrdkitを使います!

準備

まず、適当なsmilesを準備します。

import pandas as pd
import pubchempy as pcp

properties = ['CanonicalSMILES', 'IUPACName']
benzene = pcp.get_properties(properties, 'benzene', 'name', as_dataframe=True)
toluene = pcp.get_properties(properties, 'toluene', 'name', as_dataframe=True)
df = pd.concat([benzene,toluene])
display(df)

スクリーンショット 2022-11-16 19.52.46.png

画像に変換する関数

画像に変換し、保存してくれる関数を作ります

from rdkit import Chem
from rdkit.Chem import Draw
import openpyxl

def toImgFromSmiles(smiles, name):
    mol = Chem.MolFromSmiles(smiles)
    Draw.MolToFile(mol, f'{name}.png', size=(300, 300))

画像をエクセルのカラムに挿入する関数

from openpyxl.drawing.image import Image as XLImage

def add_image(worksheet, smiles_column, image_column):
    ws = worksheet
    # 行数を取得
    R_NUM = len(list(ws.rows))

    for i in range(1, R_NUM):
        idx = i + 1
        # smilesが入ってるカラム名(ex. A1, C5)
        smiles_col_name = smiles_column + str(idx)
        image_col_name = image_column + str(idx)

        smiles = ws[smiles_col_name].value
        if smiles == None: continue
        print(smiles)

        try:
            # 画像作成
            toImgFromSmiles(smiles, smiles_col_name)
            img = XLImage(f'{smiles_col_name}.png')
            img.width = 200
            img.height = 200

            # 画像を貼り付ける
            ws.add_image(img, image_col_name)

            # セルの高さを調整
            ws.row_dimensions[idx].height = img.height
        except FileNotFoundError as e:
            print('error ', e)
            break

いざ実行

import openpyxl

df.insert(2, 'img', '')
file_name = 'dataset.xlsx'

df.to_excel(file_name, index=False)
wb = openpyxl.load_workbook(file_name)
ws = wb.active

# Excelは左からA列,B列,C列,,,
add_image(ws, 'A', 'C')

# 保存
wb.save(file_name)

dataset.xlsx

ちゃんと出力されていますね!
スクリーンショット 2022-11-16 21.02.17.png

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1