| import os |
| import pickle |
| import numpy as np |
| import pandas as pd |
| import torch |
| import torch.nn as nn |
| from tqdm import tqdm |
| from unimol_tools import UniMolRepr |
| import os, sys, contextlib |
|
|
| @contextlib.contextmanager |
| def suppress_stdout_stderr(): |
| """with 块内所有 print / tqdm / warning 都不会显示""" |
| with open(os.devnull, 'w') as devnull: |
| old_out, old_err = sys.stdout, sys.stderr |
| sys.stdout, sys.stderr = devnull, devnull |
| try: |
| yield |
| finally: |
| sys.stdout, sys.stderr = old_out, old_err |
|
|
| def get_unimol_embeddings(smiles_list, output_file="UniMol_emb512.pkl", |
| model_name='unimolv1', model_size='84m', |
| remove_hs=False, batch_size=32): |
| """ |
| 使用Uni-Mol模型为SMILES列表生成分子嵌入,并保存为pickle文件 |
| |
| 参数: |
| smiles_list (list): SMILES字符串列表 |
| output_file (str): 输出pickle文件路径 |
| model_name (str): 模型名称,可选'unimolv1'或'unimolv2' |
| model_size (str): 模型大小,仅在使用unimolv2时有效 |
| remove_hs (bool): 是否移除氢原子 |
| batch_size (int): 批处理大小 |
| |
| 返回: |
| dict: 包含SMILES及其对应嵌入的字典 |
| """ |
| |
| clf = UniMolRepr( |
| data_type='molecule', |
| remove_hs=remove_hs, |
| model_name=model_name, |
| model_size=model_size |
| ) |
| |
| |
| embeddings_dict = {} |
| error_smiles = [] |
| |
| |
| total_batches = (len(smiles_list) + batch_size - 1) // batch_size |
| |
| print(f"开始生成{len(smiles_list)}个SMILES的嵌入表示...") |
| |
| print("开始") |
| |
| for i in tqdm(range(total_batches), desc="处理批次"): |
| batch = smiles_list[i*batch_size : (i+1)*batch_size] |
| |
| try: |
| |
| batch_repr = clf.get_repr(batch, return_atomic_reprs=False) |
| |
| |
| for idx, smiles in enumerate(batch): |
| embeddings_dict[smiles] = batch_repr['cls_repr'][idx] |
| |
| except Exception as e: |
| print(f"处理批次 {i+1}/{total_batches} 时发生错误: {str(e)}") |
| |
| error_smiles.extend(batch) |
| |
| |
| with open(output_file, 'wb') as f: |
| pickle.dump(embeddings_dict, f) |
| |
| print(f"嵌入生成完成!共处理 {len(smiles_list)} 个SMILES," |
| f"{len(smiles_list) - len(error_smiles)} 个成功," |
| f"{len(error_smiles)} 个失败。") |
| print(f"嵌入结果已保存至 {output_file}") |
| |
| if error_smiles: |
| print(f"处理失败的SMILES已记录。") |
| |
| return embeddings_dict |
|
|
| |
| if __name__ == "__main__": |
| |
| |
| unique_smiles = [ |
| "CC(=O)OC1=CC=CC=C1C(=O)O", |
| "CN1C=NC2=C1C(=O)N(C(=O)N2C)C" |
| ] |
| unique_smiles = pd.read_csv('./LINCS2020/LINCS2020_smiles.csv')['SMILES'].tolist() |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| embeddings = get_unimol_embeddings( |
| smiles_list=unique_smiles, |
| output_file="embeddings/UniMolV2_emb1024.pkl", |
| model_name='unimolv2', |
| model_size='310m', |
| remove_hs=False, |
| batch_size=32 |
| ) |
|
|
| |
| sample_smiles = unique_smiles[0] |
| print(f"SMILES: {sample_smiles}") |
| print(f"嵌入向量: {embeddings[sample_smiles]}") |
| print(f"嵌入维度: {len(embeddings[sample_smiles])}") |
|
|
|
|
|
|