diff --git "a/data/dataset_QSAR.csv" "b/data/dataset_QSAR.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_QSAR.csv" @@ -0,0 +1,19526 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"QSAR","deepmodeling/unimol_tools","setup.py",".py","1574","55","""""""Install script for setuptools."""""" + +from setuptools import find_packages +from setuptools import setup + +setup( + name=""unimol_tools"", + version=""0.1.5"", + description=( + ""unimol_tools is a Python package for property prediction with Uni-Mol in molecule, materials and protein."" + ), + long_description=open('README.md').read(), + long_description_content_type='text/markdown', + author=""DP Technology"", + author_email=""unimol@dp.tech"", + license=""The MIT License"", + url=""https://github.com/deepmodeling/unimol_tools"", + packages=find_packages( + where='.', + exclude=[ + ""build"", + ""dist"", + ], + ), + install_requires=[ + ""numpy<2.3.0,>=2.0.0"", + ""pandas>=2.2.2"", + ""torch>=2.4.0"", + ""joblib"", + ""rdkit>=2024.3.4"", + ""pyyaml"", + ""addict"", + ""scikit-learn>=1.5.0"", + ""numba"", + ""tqdm"", + ""hydra-core"", + ""omegaconf"", + ""tensorboard"", + ""lmdb"", + ], + python_requires="">=3.9"", + include_package_data=True, + classifiers=[ + ""Development Status :: 5 - Production/Stable"", + ""Intended Audience :: Science/Research"", + ""License :: OSI Approved :: Apache Software License"", + ""Operating System :: POSIX :: Linux"", + ""Programming Language :: Python :: 3.7"", + ""Programming Language :: Python :: 3.8"", + ""Programming Language :: Python :: 3.9"", + ""Programming Language :: Python :: 3.10"", + ""Topic :: Scientific/Engineering :: Artificial Intelligence"", + ], +) +","Python" +"QSAR","deepmodeling/unimol_tools","docs/source/quickstart.md",".md","21639","639","# Quick start + +Quick start for UniMol Tools. + +## Molecule property prediction + +To train a model, you need to provide training data containing molecules represented as SMILES strings and corresponding target values. Targets can be real numbers for regression or binary values (0s and 1s) for classification. Leave target values blank for instances where they are unknown. + +The model can be trained either on a single target (""single tasking"") or on multiple targets simultaneously (""multi-tasking""). + +The data file can be a **CSV file with a header row**. The CSV format should have `SMILES` as input, followed by `TARGET` as the label. Note that the label is named with the `TARGET` prefix when the task involves multilabel (regression/classification). For example: + +| SMILES | TARGET | +| ----------------------------------------------- | ------ | +| NCCCCC(NC(CCc1ccccc1)C(=O)O)C(=O)N2CCCC2C(=O)O | 0 | +| COc1cc(CN2CCCCC2)cc2cc(C(=O)O)c(=O)oc12 | 1 | +| CCN(CC)C(C)CN1c2ccccc2Sc3c1cccc3 | 1 | +|... | ... | + +custom dict can also as the input. The dict format should be like + +```python +{'atoms':[['C','C'],['C','H','O']], 'coordinates':[coordinates_1,coordinates_2]} +``` +Here is an example to train a model and make a prediction. When using Unimol V2, set `model_name='unimolv2'`. +```python +from unimol_tools import MolTrain, MolPredict +clf = MolTrain(task='classification', + data_type='molecule', + epochs=10, + batch_size=16, + metrics='auc', + model_name='unimolv1', # avaliable: unimolv1, unimolv2 + model_size='84m', # work when model_name is unimolv2. avaliable: 84m, 164m, 310m, 570m, 1.1B. + ) +pred = clf.fit(data = train_data) +# currently support data with smiles based csv/txt file + +clf = MolPredict(load_model='../exp') +res = clf.predict(data = test_data) +``` + +### Command-line utilities + +Training, prediction, and representation can also be launched from the +command line by overriding options in the YAML config files. + +#### Training +```bash +python -m unimol_tools.cli.run_train \ + train_path=train.csv \ + task=regression \ + save_path=./exp \ + smiles_col=smiles \ + target_cols=[target1] \ + epochs=10 \ + learning_rate=1e-4 \ + batch_size=16 \ + kfold=5 +``` + +#### Prediction +```bash +python -m unimol_tools.cli.run_predict load_model=./exp data_path=test.csv +``` + +#### Representation +```bash +python -m unimol_tools.cli.run_repr data_path=test.csv smiles_col=smiles +``` + +## Uni-Mol molecule and atoms level representation + +Uni-Mol representation can easily be achieved as follow. + +```python +import numpy as np +from unimol_tools import UniMolRepr +# single smiles unimol representation +clf = UniMolRepr(data_type='molecule', # avaliable: molecule, oled, pocket. Only for unimolv1. + remove_hs=False, + model_name='unimolv1', # avaliable: unimolv1, unimolv2 + model_size='84m', # work when model_name is unimolv2. avaliable: 84m, 164m, 310m, 570m, 1.1B. + ) +smiles = 'c1ccc(cc1)C2=NCC(=O)Nc3c2cc(cc3)[N+](=O)[O]' +smiles_list = [smiles] +unimol_repr = clf.get_repr(smiles_list, return_atomic_reprs=True) +# CLS token repr +print(np.array(unimol_repr['cls_repr']).shape) +# atomic level repr, align with rdkit mol.GetAtoms() +print(np.array(unimol_repr['atomic_reprs']).shape) + +# For the pocket, please select and extract the atoms nearby; the total number of atoms should preferably not exceed 256. +clf = UniMolRepr(data_type='pocket', + remove_hs=False, + ) +pocket_dict = { + 'atoms': atoms, + 'coordinates': coordinates, + 'residue': residue, # Optional +} +unimol_repr = clf.get_repr(pocket_dict, return_atomic_reprs=True) + +``` +## Molecule pretraining + +Uni-Mol can be pretrained from scratch using the ``run_pretrain`` utility. The +script is driven by Hydra, so configuration options are supplied on the command +line. The examples below demonstrate common setups for LMDB and CSV inputs. + +### LMDB dataset + +```bash +torchrun --standalone --nproc_per_node=NUM_GPUS \ + -m unimol_tools.cli.run_pretrain \ + dataset.train_path=train.lmdb \ + dataset.valid_path=valid.lmdb \ + dataset.data_type=lmdb \ + dataset.dict_path=dict.txt \ + training.total_steps=10000 \ + training.batch_size=16 \ + training.update_freq=1 +``` + +`dataset.dict_path` is optional. The effective batch size is +`n_gpu * training.batch_size * training.update_freq`. + +### CSV dataset + +```bash +torchrun --standalone --nproc_per_node=NUM_GPUS \ + -m unimol_tools.cli.run_pretrain \ + dataset.train_path=train.csv \ + dataset.valid_path=valid.csv \ + dataset.data_type=csv \ + dataset.smiles_column=smiles \ + training.total_steps=10000 \ + training.batch_size=16 \ + training.update_freq=1 +``` + +To scale across multiple machines, include the appropriate `torchrun` +arguments, e.g. `--nnodes`, `--node_rank`, `--master_addr` and +`--master_port`. + +Checkpoints and the dictionary are written to the output directory. When GPU +memory is limited, increase `training.update_freq` to accumulate gradients while +keeping the effective batch size `n_gpu * training.batch_size * training.update_freq`. + +## Continue training (Re-train) + +```python +clf = MolTrain( + task='regression', + data_type='molecule', + epochs=10, + batch_size=16, + save_path='./model_dir', + remove_hs=False, + target_cols='TARGET', + ) +pred = clf.fit(data = train_data) +# After train a model, set load_model_dir='./model_dir' to continue training + +clf2 = MolTrain( + task='regression', + data_type='molecule', + epochs=10, + batch_size=16, + save_path='./retrain_model_dir', + remove_hs=False, + target_cols='TARGET', + load_model_dir='./model_dir', + ) + +pred2 = clf.fit(data = retrain_data) +``` + +## Distributed Data Parallel (DDP) Training + +Uni-Mol Tools now supports Distributed Data Parallel (DDP) training using PyTorch. DDP allows you to train models across multiple GPUs or nodes, significantly speeding up the training process. + +### Parameters +- `use_ddp`: bool, default=True, whether to enable Distributed Data Parallel (DDP). +- `use_gpu`: str, default='all', specifies which GPUs to use. `'all'` means all available GPUs, while `'0,1,2'` means using GPUs 0, 1, and 2. + +### Example Usage +To enable DDP, ensure your environment supports distributed training (e.g., PyTorch with distributed support). Set `use_ddp=True` and specify the GPUs using the `use_gpu` parameter when initializing the `MolTrain` class. + +#### Example for Training + +```python +from unimol_tools import MolTrain + +# Initialize the training class with DDP enabled +if __name__ == '__main__': + clf = MolTrain( + task='regression', + data_type='molecule', + epochs=10, + batch_size=16, + save_path='./model_dir', + remove_hs=False, + target_cols='TARGET', + use_ddp=True, + use_gpu=""all"" + ) + pred = clf.fit(data = train_data) +``` + +#### Example for Molecular Representation + +```python +from unimol_tools import UniMolRepr + +# Initialize the UniMolRepr class with DDP enabled +if __name__ == '__main__': + repr_model = UniMolRepr( + data_type='molecule', + batch_size=32, + remove_hs=False, + model_name='unimolv2', + model_size='84m', + use_ddp=True, # Enable Distributed Data Parallel + use_gpu='0,1' # Use GPU 0 and 1 + ) + + unimol_repr = repr_model.get_repr(smiles_list, return_atomic_reprs=True) + + # CLS token representation + print(unimol_repr['cls_repr']) + # Atomic-level representation + print(unimol_repr['atomic_reprs']) +``` + +- **Important:** When the number of SMILES strings is small, it is not recommended to use DDP for the `get_repr` method. Communication overhead between processes may outweigh the benefits of parallel computation, leading to slower performance. In such cases, consider disabling DDP by setting `use_ddp=False`. + +### Why use `if __name__ == '__main__':` + +In Python, when using multiprocessing (e.g., PyTorch's `DistributedDataParallel` or other libraries requiring multiple processes), it is recommended to use the `if __name__ == '__main__':` idiom. This is because, in a multiprocessing environment, child processes may re-import the main module. Without this idiom, the code in the main module could be executed multiple times, leading to unexpected behavior or errors. + +#### Common Error + +If you do not use `if __name__ == '__main__':`, you might encounter the following error: + +```Python +RuntimeError: + An attempt has been made to start a new process before the + current process has finished its bootstrapping phase. + + This probably means that you are not using fork to start your + child processes and you have forgotten to use the proper idiom + in the main module: + + if __name__ == '__main__': + freeze_support() + ... + + The ""freeze_support()"" line can be omitted if the program + is not going to be frozen to produce an executable. +``` + +To avoid this error, ensure that all code requiring multiprocessing is enclosed within the if `__name__ == '__main__'`: block. + +### Notes +- For multi-node training, the `MASTER_ADDR` and `MASTER_PORT` environment variables can be configured as below. + +```bash +export MASTER_ADDR='localhost' +export MASTER_PORT='19198' +``` + +## Simple examples of five tasks +Currently unimol_tools supports five types of fine-tuning tasks: `classification`, `regression`, `multiclass`, `multilabel_classification`, `multilabel_regression`. + +The datasets used in the examples are all open source and available, including +- Ames mutagenicity. The dataset includes 6512 compounds and corresponding binary labels from Ames Mutagenicity results. The dataset is available at https://weilab.math.msu.edu/DataLibrary/2D/. +- ESOL (delaney) is a standard regression dataset containing structures and water solubility data for 1128 compounds. The dataset is available at https://weilab.math.msu.edu/DataLibrary/2D/ and https://huggingface.co/datasets/HR-machine/ESol. +- Tox21 Data Challenge 2014 is designed to help scientists understand the potential of the chemicals and compounds being tested through the Toxicology in the 21st Century initiative to disrupt biological pathways in ways that may result in toxic effects, which includes 12 date sets. The official web site is https://tripod.nih.gov/tox21/challenge/. The datasets is available at https://moleculenet.org/datasets-1 and https://www.kaggle.com/datasets/maksiamiogan/tox21-dataset. +- Solvation free energy (FreeSolv). SMILES are provided. The dataset is available at https://weilab.math.msu.edu/DataLibrary/2D/. +- Vector-QM24 (VQM24) dataset. Quantum chemistry dataset of ~836 thousand small organic and inorganic molecules. The dataset is available at https://zenodo.org/records/15442257. + +### Example of classification +You can use a dictionary as input. The default smiles column name is **'SMILES'** and the target column name is **'target'**. You can also customize it with `smiles_col` and `target_cols`. + +```Python +import pandas as pd +from unimol_tools import MolTrain, MolPredict + +# Load the dataset +df = pd.read_csv('../datasets/Ames/Ames.csv') + +df = df.drop(columns=['CAS_NO']).rename(columns={'Activity': 'target'}) + +# Divide the training set and test set +train_df = df.sample(frac=0.8, random_state=42) +test_df = df.drop(train_df.index) + +train_df_dict = train_df.to_dict(orient='list') +test_df_dict = test_df.to_dict(orient='list') + +clf = MolTrain(task='classification', + data_type='molecule', + epochs=20, + batch_size=16, + metrics='auc', + smiles_col='Canonical_Smiles', + ) + +clf.fit(train_df_dict) + +predictor = MolPredict(load_model='./exp') + +pred = predictor.predict(test_df_dict['Canonical_Smiles']) +``` + +### Example of regression +You can directly use the csv file path as input. The default recognized smiles column name is **'SMILES'** and the target column name is **'TARGET'**. The column names can be customized by `smiles_col` and `target_cols`. + +```python +from unimol_tools import MolTrain, MolPredict + +# Load the dataset +train_data_path = '../datasets/ESol/train_data.csv' +test_data_path = '../datasets/ESol/test_data.csv' + +reg = MolTrain(task='regression', + data_type='molecule', + epochs=20, + batch_size=32, + metrics='mae', + smiles_col='smiles', + target_cols=['ESOL predicted log solubility in mols per litre'], + save_path='./exp_esol', + ) + +reg.fit(train_data_path) + +predictor = MolPredict(load_model='./exp_esol') +y_pred = predictor.predict(data=test_data_path) +``` + +It is also possible to use a list of atoms and a list of coordinates directly as input, with the column names **'atoms'** and **'coordinates'**. The smiles list is optional, but is required if scaffold is used as the grouping method. Atoms list supports either atom type or atomic number input, for example, 'atoms':[['C', 'C'],['C', 'H', 'O']] or 'atoms':[[6, 6],[6, 1, 8]]. + +```python +import numpy as np +from unimol_tools import MolTrain, MolPredict +from rdkit import Chem + +# Load the dataset +data = np.load('../datasets/DMC.npz', allow_pickle=True) +atoms_all = data['atoms'] +coordinates_all = data['coordinates'] +smiles_all = data['graphs'] +all_targets = data['Etot'] + +# Filter illegal smiles data +valid_smiles = [] +valid_atoms = [] +valid_coordinates = [] +valid_targets = [] +for smiles, target, atoms, coordinates in zip(smiles_all, all_targets, atoms_all, coordinates_all): + try: + mol = Chem.MolFromSmiles(smiles) + if mol is not None: + valid_smiles.append(smiles) + valid_atoms.append(atoms) + valid_coordinates.append(coordinates) + valid_targets.append(target) + except Exception as e: + print(f""Invalid SMILES: {smiles}, Error: {e}"") + +# Divide the training set and test set +num_molecules = len(valid_smiles) +np.random.seed(42) +indices = np.random.permutation(num_molecules) +train_end = int(0.8 * num_molecules) +train_val_idx = indices[:train_end] +test_idx = indices[train_end:] + +train_val_smiles = [valid_smiles[i] for i in train_val_idx] +test_smiles = [valid_smiles[i] for i in test_idx] +train_val_atoms = [valid_atoms[i] for i in train_val_idx] +test_atoms = [valid_atoms[i] for i in test_idx] +train_val_coordinates = [valid_coordinates[i] for i in train_val_idx] +test_coordinates = [valid_coordinates[i] for i in test_idx] + +train_val_targets = [valid_targets[i] for i in train_val_idx] +test_targets = [valid_targets[i] for i in test_idx] + +train_val_data = { + 'target': train_val_targets, + 'atoms': train_val_atoms, + 'coordinates': train_val_coordinates, + 'SMILES': train_val_smiles, +} +test_data = { + 'SMILES': test_smiles, + 'atoms': test_atoms, + 'coordinates': test_coordinates, +} + +reg = MolTrain(task='regression', + data_type='molecule', + epochs=20, + batch_size=32, + metrics='mae', + save_path='./exp', + ) + +reg.fit(train_val_data) + +predictor = MolPredict(load_model='./exp') +y_pred = predictor.predict(data=test_data, save_path='./pre') # Specify save_path to store prediction results +``` + +### Example of multiclass + +```python +import pandas as pd +from unimol_tools import MolTrain, MolPredict +import numpy as np + +# Load the dataset +df = pd.read_csv('../datasets/ESOL/ESOL.csv') + +data_dict = { + 'SMILES': df['smiles'].tolist(), + 'target': df['Number of H-Bond Donors'].tolist() +} + +data_dict['SMILES'] = [smiles for i, smiles in enumerate(data_dict['SMILES']) if data_dict['target'][i] <= 4] +data_dict['target'] = [target for target in data_dict['target'] if target <= 4] + +# Divide the training set and test set +num_molecules = len(data_dict['SMILES']) +np.random.seed(42) +indices = np.random.permutation(num_molecules) +train_end = int(0.8 * num_molecules) +train_val_idx = indices[:train_end] +test_idx = indices[train_end:] + +train_val_dict = { + 'SMILES': [data_dict['SMILES'][i] for i in train_val_idx], + 'target': [data_dict['target'][i] for i in train_val_idx], +} +test_dict = { + 'SMILES': [data_dict['SMILES'][i] for i in test_idx], + 'target': [data_dict['target'][i] for i in test_idx], +} + +mclf = MolTrain(task='multiclass', + data_type='molecule', + epochs=20, + batch_size=32, + metrics='acc', + save_path='./exp', + ) + +mclf.fit(train_val_dict) + +predictor = MolPredict(load_model='./exp') +y_pred = predictor.predict(data=test_dict) +``` + +### Example of multilabel_classification + +```python +import pandas as pd +from unimol_tools import MolTrain, MolPredict + +# Load the dataset +df = pd.read_csv('../datasets/tox21.csv') + +# Fill missing values ​​with 0 +df.fillna(0, inplace=True) + +df.drop(columns=['mol_id'], inplace=True) + +# Divide the training set and test set +train_df = df.sample(frac=0.8, random_state=42) +test_df = df.drop(train_df.index) + +train_df_dict = train_df.to_dict(orient='list') +test_df_dict = test_df.to_dict(orient='list') + +mlclf = MolTrain(task='multilabel_classification', + data_type='molecule', + epochs=20, + batch_size=32, + metrics='auc', + smiles_col='smiles', + target_cols=[col for col in df.columns if col != 'smiles'], + ) +mlclf.fit(train_df_dict) + +predictor = MolPredict(load_model='./exp') +pred = predictor.predict(test_df_dict['smiles']) +``` + +It also supports directly using the sdf file path as input. The following example reads it in advance due to preprocessing missing values. + +```python +from unimol_tools import MolTrain, MolPredict +from rdkit.Chem import PandasTools + +# Load the dataset +data_path = '../datasets/tox21.sdf' + +data = PandasTools.LoadSDF(data_path) + +# Fill missing values ​​with 0 +data['SR-HSE'] = data['SR-HSE'].fillna(0) +data['NR-AR'] = data['NR-AR'].fillna(0) + +mlclf = MolTrain(task='multilabel_classification', + data_type='molecule', + epochs=20, + batch_size=32, + metrics='auc', + target_cols=['SR-HSE', 'NR-AR'], + save_path='./exp_sdf', + ) +mlclf.fit(data) +``` + +### Example of multilabel_regression + +```python +from unimol_tools import MolTrain, MolPredict + +# Load the dataset +data_path = '../datasets/FreeSolv/SAMPL.csv' + +mreg = MolTrain(task='multilabel_regression', + data_type='molecule', + epochs=20, + batch_size=32, + metrics='mae', + smiles_col='smiles', + target_cols='expt,calc', + save_path='./exp_csv', + ) + +mreg.fit(data_path) +``` + +```python +from unimol_tools import MolTrain, MolPredict +import pandas as pd +import numpy as np + +# Load the dataset +df = pd.read_csv('../datasets/FreeSolv/SAMPL.csv') + +data_dict = { + 'SMILES': df['smiles'].tolist(), + 'target': [df['expt'].tolist(), df['calc'].tolist()] +} + +# Divide the training set and test set +num_molecules = len(data_dict['SMILES']) +np.random.seed(42) +indices = np.random.permutation(num_molecules) +train_end = int(0.8 * num_molecules) +train_val_idx = indices[:train_end] +test_idx = indices[train_end:] + +train_val_dict = { + 'SMILES': [data_dict['SMILES'][i] for i in train_val_idx], + 'target': [data_dict['target'][0][i] for i in train_val_idx], +} +test_dict = { + 'SMILES': [data_dict['SMILES'][i] for i in test_idx], + 'target': [data_dict['target'][0][i] for i in test_idx], +} + +mreg = MolTrain(task='multilabel_regression', + data_type='molecule', + epochs=20, + batch_size=32, + metrics='mae', + save_path='./exp_dict', + ) + +mreg.fit(train_val_dict) + +predictor = MolPredict(load_model='./exp_dict') +y_pred = predictor.predict(data=test_dict) +``` + +```python +from unimol_tools import MolTrain, MolPredict +import pandas as pd +import numpy as np + +# Load the dataset +df = pd.read_csv('../datasets/FreeSolv/SAMPL.csv') + +data_dict = { + 'SMILES': df['smiles'].tolist(), + 'expt': df['expt'].tolist(), + 'calc': df['calc'].tolist() +} + +# Divide the training set and test set +num_molecules = len(data_dict['SMILES']) +np.random.seed(42) +indices = np.random.permutation(num_molecules) +train_end = int(0.8 * num_molecules) +train_val_idx = indices[:train_end] +test_idx = indices[train_end:] + +train_val_dict = { + 'SMILES': [data_dict['SMILES'][i] for i in train_val_idx], + 'expt': [data_dict['expt'][i] for i in train_val_idx], + 'calc': [data_dict['calc'][i] for i in train_val_idx], +} +test_dict = { + 'SMILES': [data_dict['SMILES'][i] for i in test_idx], + 'expt': [data_dict['expt'][i] for i in test_idx], + 'calc': [data_dict['calc'][i] for i in test_idx], +} + +mreg = MolTrain(task='multilabel_regression', + data_type='molecule', + epochs=20, + batch_size=32, + metrics='mae', + target_cols=['expt', 'calc'], + save_path='./exp_dict', + ) + +mreg.fit(train_val_dict) + +predictor = MolPredict(load_model='./exp_dict') +y_pred = predictor.predict(data=test_dict, save_path='./pre_dict') +``` +","Markdown" +"QSAR","deepmodeling/unimol_tools","docs/source/installation.md",".md","1596","50","# Installation + +## Install +- pytorch is required, please install pytorch according to your environment. if you are using cuda, please install pytorch with cuda. More details can be found at https://pytorch.org/get-started/locally/ +- currently, rdkit needs with numpy<2.0.0, please install rdkit with numpy<2.0.0. + +### Option 1: Installing from PyPi (Recommended) + +```bash +pip install unimol_tools +``` + +We recommend installing ```huggingface_hub``` so that the required unimol models can be automatically downloaded at runtime! It can be install by + +```bash +pip install huggingface_hub +``` + +`huggingface_hub` allows you to easily download and manage models from the Hugging Face Hub, which is key for using Uni-Mol models. + +### Option 2: Installing from source + +```python +## Dependencies installation +pip install -r requirements.txt + +## Clone repository +git clone https://github.com/deepmodeling/unimol_tools.git +cd unimol_tools + +## Install +python setup.py install +``` + +### Models in Huggingface + +The Uni-Mol pretrained models can be found at [dptech/Uni-Mol-Models](https://huggingface.co/dptech/Uni-Mol-Models/tree/main). + +If the download is slow, you can use other mirrors, such as: + +```bash +export HF_ENDPOINT=https://hf-mirror.com +``` + +By default `unimol_tools` first tries the official Hugging Face endpoint. If that fails and `HF_ENDPOINT` is not set, it automatically retries using `https://hf-mirror.com`. Set `HF_ENDPOINT` to use a specific endpoint. + +## Bohrium notebook + +Uni-Mol images can be avaliable on the online notebook platform [Bohirum notebook](https://nb.bohrium.dp.tech/). + ","Markdown" +"QSAR","deepmodeling/unimol_tools","docs/source/requirements.md",".md","733","9","# Requirements + +For small datasets (~1000 molecules), it is possible to train models within a few minutes on a standard laptop with CPUs only. However, for larger datasets and larger Uni-Mol models, we recommend using a GPU for significantly faster training. + +Notice: [Uni-Core](https://github.com/dptech-corp/Uni-Core) is needed, please install it first. Current Uni-Core requires torch>=2.0.0 by default, if you want to install other version, please check its [Installation Documentation](https://github.com/dptech-corp/Uni-Core#installation). + + +Uni-Mol is uses Python 3.8+ and all models are built with [PyTorch](https://pytorch.org/). See [Installation](#installation) for details on how to install Uni-Mol and its dependencies. +","Markdown" +"QSAR","deepmodeling/unimol_tools","docs/source/features.md",".md","257","12","# New Features + +## 2025-03-28 +Unimol_tools now support Distributed Data Parallel (DDP)! + +## 2024-11-22 +Unimol V2 has been added to Unimol_tools! + +## 2024-06-25 + +Unimol_tools has been publish to pypi! Huggingface has been used to manage the pretrain models. +","Markdown" +"QSAR","deepmodeling/unimol_tools","docs/source/school.md",".md","2359","26","# Uni-Mol School + +Welcome to Uni-Mol School! This course is designed to provide comprehensive training on Uni-Mol, a powerful tool for molecular modeling and simulations. + +## Course Introduction +The properties of drugs are determined by their three-dimensional structures, which are crucial for their efficacy and absorption. Drug design requires consideration of molecular diversity. Current Molecular Representation Learning (MRL) models mainly utilize one-dimensional or two-dimensional data, with limited capability to integrate 3D information. + +Uni-Mol, developed by the DP Technology team, is the first general large-scale 3D MRL framework in the field of drug design, expanding the application scope and representation capabilities of MRL. This framework consists of two models trained on billions of molecular 3D conformations and millions of protein pocket data, respectively. It has shown excellent performance in various molecular property prediction tasks, especially in 3D-related tasks. Besides drug design, Uni-Mol can also predict the properties of materials, such as gas adsorption performance of MOF materials and optical properties of OLED molecules. + +## Course Content +| Topic | Course Content | Instructor | +|-------|----------------|------------| +| Introduction to Uni-Mol | Uni-Mol molecular 3D representation learning framework and pre-trained models | Chen Letian | +| Uni-Mol for Materials Science | Case study of Uni-Mol in predicting the properties of battery materials | Chen Letian | +| | 3D Representation Learning Framework and Pre-trained Models for Nanoporous Materials | Chen Letian | +| | Efficient Screening of Ir(III) Complex Emitters: A Study Combining Machine Learning and Computational Analysis | Chen Letian | +| | Application of 3D Molecular Pre-trained Model Uni-Mol in Flow Batteries | Xie Qiming | +| | Materials Science Uni-Mol Notebook Case Study | | +| Uni-Mol for Biomedical Science | Application of Uni-Mol in Molecular Docking | Zhou Gengmo | +| | Application of Uni-Mol in Molecular Generation | Song Ke | +| | Biomedical Science Uni-Mol Notebook Case Study | | + +## How to Enroll +Enroll now and start your journey with Uni-Mol! [Click here to enroll](https://bohrium.dp.tech/courses/6134196349?tab=courses) + +Don't miss this opportunity to advance your knowledge and skills in molecular modeling with Uni-Mol!","Markdown" +"QSAR","deepmodeling/unimol_tools","docs/source/conf.py",".py","1721","61","# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +project = 'unimol_tools' +copyright = '2023, cuiyaning' +author = 'cuiyaning' +release = '0.1.1' + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration + +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.viewcode', + 'myst_parser', + ] + +templates_path = ['_templates'] +exclude_patterns = [] + +highlight_language = 'python' + + +# List of modules to be mocked up. This is useful when some external +# dependencies are not met at build time and break the building process. +autodoc_mock_imports = [ + 'rdkit', + 'unicore', + 'torch', + 'sklearn', +] + + +# -- Options for HTML output ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +html_theme = 'sphinx_rtd_theme' +html_static_path = ['_static'] + +# -- Autodoc configuration --------------------------------------------------- + +autoclass_content = 'class' + +# 显式地设置成员的顺序,确保构造函数的参数首先显示 +autodoc_member_order = 'bysource' + +# 设置构造函数的默认选项,包括显示参数 + +autodoc_default_options = { + 'members': True, + 'special-members': '__init__', + #'undoc-members': False, + 'private-members': True, + #'show-inheritance': False, +} +","Python" +"QSAR","deepmodeling/unimol_tools","docs/source/examples.md",".md","1965","22","# Examples + +Welcome to the examples section! On our platform Bohrium, we offer a variety of notebook cases for studying Uni-Mol. These notebooks provide practical examples and applications of Uni-Mol in different scientific fields. You can explore these notebooks to gain hands-on experience and deepen your understanding of Uni-Mol. + +## Uni-Mol Notebooks on Bohrium +Explore our collection of Uni-Mol notebooks on Bohrium: [Uni-Mol Notebooks](https://bohrium.dp.tech/search?searchKey=UniMol&%3BactiveTab=notebook&activeTab=notebook) + +### Uni-Mol for QSAR (Quantitative Structure-Activity Relationship) +Uni-Mol can be used to predict the biological activity of compounds based on their chemical structure. These notebooks demonstrate how to apply Uni-Mol for QSAR tasks: +- [QSAR Example 1](https://bohrium.dp.tech/notebooks/7141701322) +- [QSAR Example 2](https://bohrium.dp.tech/notebooks/9919429887) + +### Uni-Mol for OLED Properties Predictions +Organic Light Emitting Diodes (OLEDs) are used in various display technologies. Uni-Mol can predict the properties of OLED molecules, aiding in the design of more efficient materials. Check out these notebooks for detailed examples: +- [OLED Properties Prediction Example 1](https://bohrium.dp.tech/notebooks/2412844127) +- [OLED Properties Prediction Example 2](https://bohrium.dp.tech/notebooks/7637046852) + +### Uni-Mol Predicts Liquid Flow Battery Solubility +Liquid flow batteries are a promising technology for energy storage. Uni-Mol can predict the solubility of compounds used in these batteries, helping to optimize their performance. Explore this notebook to see how Uni-Mol is applied in this context: +- [Liquid Flow Battery Solubility Prediction](https://bohrium.dp.tech/notebooks/7941779831) + +These examples provide a glimpse into the powerful capabilities of Uni-Mol in various scientific applications. We encourage you to explore these notebooks and experiment with Uni-Mol to discover its full potential.","Markdown" +"QSAR","deepmodeling/unimol_tools","unimol_tools/train.py",".py","13915","316","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import argparse +import copy +import json +import logging +import os + +import joblib +import numpy as np +import pandas as pd +from omegaconf import DictConfig, OmegaConf + +from .data import DataHub +from .models import NNModel +from .tasks import Trainer +from .utils import YamlHandler, logger + + +class MolTrain(object): + """"""A :class:`MolTrain` class is responsible for interface of training process of molecular data."""""" + + def __init__( + self, + cfg: DictConfig | None = None, + task='classification', + data_type='molecule', + epochs=10, + learning_rate=1e-4, + batch_size=16, + early_stopping=5, + metrics=""none"", + split='random', # random, scaffold, group, stratified + split_group_col='scaffold', # only active with group split + kfold=5, + save_path='./exp', + remove_hs=False, + smiles_col='SMILES', + target_cols=None, + target_col_prefix='TARGET', + target_anomaly_check=False, + smiles_check=""filter"", + target_normalize=""auto"", + max_norm=5.0, + use_cuda=True, + use_amp=True, + use_ddp=False, + use_gpu=""all"", + freeze_layers=None, + freeze_layers_reversed=False, + load_model_dir=None, # load model for transfer learning + model_name='unimolv1', + model_size='84m', + pretrained_model_path=None, + pretrained_dict_path=None, + conf_cache_level=1, + **params, + ): + """""" + Initialize a :class:`MolTrain` class. + + :param task: str, default='classification', currently support [`classification`, `regression`, `multiclass`, `multilabel_classification`, `multilabel_regression`]. + :param data_type: str, default='molecule', currently support molecule, oled. + :param epochs: int, default=10, number of epochs to train. + :param learning_rate: float, default=1e-4, learning rate of optimizer. + :param batch_size: int, default=16, batch size of training. + :param early_stopping: int, default=5, early stopping patience. + :param metrics: str, default='none', metrics to evaluate model performance. + + currently support: + + - classification: auc, auprc, log_loss, acc, f1_score, mcc, precision, recall, cohen_kappa. + + - regression: mse, pearsonr, spearmanr, mse, r2. + + - multiclass: log_loss, acc. + + - multilabel_classification: auc, auprc, log_loss, acc, mcc. + + - multilabel_regression: mae, mse, r2. + + :param split: str, default='random', split method of training dataset. currently support: random, scaffold, group, stratified, select. + + - random: random split. + + - scaffold: split by scaffold. + + - group: split by group. `split_group_col` should be specified. + + - stratified: stratified split. `split_group_col` should be specified. + + - select: use `split_group_col` to manually select the split group. Column values of `split_group_col` should be range from 0 to kfold-1 to indicate the split group. + + :param split_group_col: str, default='scaffold', column name of group split. + :param kfold: int, default=5, number of folds for k-fold cross validation. + + - 1: no split. all data will be used for training. + + :param save_path: str, default='./exp', path to save training results. + :param remove_hs: bool, default=False, whether to remove hydrogens from molecules. + :param smiles_col: str, default='SMILES', column name of SMILES. + :param target_cols: list or str, default=None, column names of target values. + :param target_col_prefix: str, default='TARGET', prefix of target column name. + :param target_anomaly_check: str, default=False, how to deal with anomaly target values. currently support: filter, none. + :param smiles_check: str, default='filter', how to deal with invalid SMILES. currently support: filter, none. + :param target_normalize: str, default='auto', how to normalize target values. 'auto' means we will choose the normalize strategy by automatic. \ + currently support: auto, minmax, standard, robust, log1p, none. + :param max_norm: float, default=5.0, max norm of gradient clipping. + :param use_cuda: bool, default=True, whether to use GPU. + :param use_amp: bool, default=True, whether to use automatic mixed precision. + :param use_ddp: bool, default=True, whether to use distributed data parallel. + :param use_gpu: str, default='all', which GPU to use. 'all' means use all GPUs. '0,1,2' means use GPU 0, 1, 2. + :param freeze_layers: str or list, frozen layers by startwith name list. ['encoder', 'gbf'] will freeze all the layers whose name start with 'encoder' or 'gbf'. + :param freeze_layers_reversed: bool, default=False, inverse selection of frozen layers + :param params: dict, default=None, other parameters. + :param load_model_dir: str, default=None, path to load model for transfer learning. + :param model_name: str, default='unimolv1', currently support unimolv1, unimolv2. + :param model_size: str, default='84m', model size. work when model_name is unimolv2. Avaliable: 84m, 164m, 310m, 570m, 1.1B. + :param pretrained_model_path: str, default=None, path to pretrained model. + :param pretrained_dict_path: str, default=None, path to pretrained model's dict file. + :param conf_cache_level: int, optional [0, 1, 2], default=1, configuration cache level to save the conformers to sdf file. + - 0: no caching. + - 1: cache if not exists. + - 2: always cache. + + """""" + if cfg is not None: + cfg_dict = OmegaConf.to_container(cfg, resolve=True) + task = cfg_dict.get('task', task) + data_type = cfg_dict.get('data_type', data_type) + epochs = cfg_dict.get('epochs', epochs) + learning_rate = cfg_dict.get('learning_rate', learning_rate) + batch_size = cfg_dict.get('batch_size', batch_size) + early_stopping = cfg_dict.get('early_stopping', early_stopping) + metrics = cfg_dict.get('metrics', metrics) + split = cfg_dict.get('split', split) + split_group_col = cfg_dict.get('split_group_col', split_group_col) + kfold = cfg_dict.get('kfold', kfold) + save_path = cfg_dict.get('save_path', save_path) + remove_hs = cfg_dict.get('remove_hs', remove_hs) + smiles_col = cfg_dict.get('smiles_col', smiles_col) + target_cols = cfg_dict.get('target_cols', target_cols) + target_col_prefix = cfg_dict.get('target_col_prefix', target_col_prefix) + target_anomaly_check = cfg_dict.get( + 'target_anomaly_check', target_anomaly_check + ) + smiles_check = cfg_dict.get('smiles_check', smiles_check) + target_normalize = cfg_dict.get('target_normalize', target_normalize) + max_norm = cfg_dict.get('max_norm', max_norm) + use_cuda = cfg_dict.get('use_cuda', use_cuda) + use_amp = cfg_dict.get('use_amp', use_amp) + use_ddp = cfg_dict.get('use_ddp', use_ddp) + use_gpu = cfg_dict.get('use_gpu', use_gpu) + freeze_layers = cfg_dict.get('freeze_layers', freeze_layers) + freeze_layers_reversed = cfg_dict.get( + 'freeze_layers_reversed', freeze_layers_reversed + ) + load_model_dir = cfg_dict.get('load_model_dir', load_model_dir) + model_name = cfg_dict.get('model_name', model_name) + model_size = cfg_dict.get('model_size', model_size) + pretrained_model_path = cfg_dict.get( + 'pretrained_model_path', pretrained_model_path + ) + pretrained_dict_path = cfg_dict.get( + 'pretrained_dict_path', pretrained_dict_path + ) + conf_cache_level = cfg_dict.get('conf_cache_level', conf_cache_level) + known_keys = { + 'task', + 'data_type', + 'epochs', + 'learning_rate', + 'batch_size', + 'early_stopping', + 'metrics', + 'split', + 'split_group_col', + 'kfold', + 'save_path', + 'remove_hs', + 'smiles_col', + 'target_cols', + 'target_col_prefix', + 'target_anomaly_check', + 'smiles_check', + 'target_normalize', + 'max_norm', + 'use_cuda', + 'use_amp', + 'use_ddp', + 'use_gpu', + 'freeze_layers', + 'freeze_layers_reversed', + 'load_model_dir', + 'model_name', + 'model_size', + 'pretrained_model_path', + 'pretrained_dict_path', + 'conf_cache_level', + } + params.update({k: v for k, v in cfg_dict.items() if k not in known_keys}) + + if load_model_dir is not None: + config_path = os.path.join(load_model_dir, 'config.yaml') + logger.info('Load config file from {}'.format(config_path)) + else: + config_path = os.path.join(os.path.dirname(__file__), 'config/default.yaml') + self.yamlhandler = YamlHandler(config_path) + config = self.yamlhandler.read_yaml() + config.task = task + config.data_type = data_type + config.epochs = epochs + config.learning_rate = learning_rate + config.batch_size = batch_size + config.patience = early_stopping + config.metrics = metrics + config.split = split + config.split_group_col = split_group_col + config.kfold = kfold + config.remove_hs = remove_hs + config.smiles_col = smiles_col + config.target_cols = target_cols + config.target_col_prefix = target_col_prefix + config.anomaly_clean = target_anomaly_check or target_anomaly_check in [ + 'filter' + ] + config.smi_strict = smiles_check in ['filter'] + config.target_normalize = target_normalize + config.max_norm = max_norm + config.use_cuda = use_cuda + config.use_amp = use_amp + config.use_ddp = use_ddp + config.use_gpu = use_gpu + config.freeze_layers = freeze_layers + config.freeze_layers_reversed = freeze_layers_reversed + config.load_model_dir = load_model_dir + config.model_name = model_name + config.model_size = model_size + config.pretrained_model_path = pretrained_model_path + config.pretrained_dict_path = pretrained_dict_path + config.conf_cache_level = conf_cache_level + self.save_path = save_path + self.config = config + + def fit(self, data): + """""" + Fit the model according to the given training data with multi datasource support, including SMILES csv file and custom coordinate data. + + For example: custom coordinate data. + + .. code-block:: python + + from unimol_tools import MolTrain + import numpy as np + custom_data ={'target':np.random.randint(2, size=100), + 'atoms':[['C','C','H','H','H','H'] for _ in range(100)], + 'coordinates':[np.random.randn(6,3) for _ in range(100)], + } + + clf = MolTrain() + clf.fit(custom_data) + """""" + self.datahub = DataHub( + data=data, is_train=True, save_path=self.save_path, **self.config + ) + self.data = self.datahub.data + self.update_and_save_config() + self.trainer = Trainer(save_path=self.save_path, **self.config) + self.model = NNModel(self.data, self.trainer, **self.config) + self.model.run() + scalar = self.data['target_scaler'] + y_pred = self.model.cv['pred'] + y_true = np.array(self.data['target']) + metrics = self.trainer.metrics + if scalar is not None: + y_pred = scalar.inverse_transform(y_pred) + y_true = scalar.inverse_transform(y_true) + + if self.config[""task""] in ['classification', 'multilabel_classification']: + threshold = metrics.calculate_classification_threshold(y_true, y_pred) + joblib.dump(threshold, os.path.join(self.save_path, 'threshold.dat')) + + self.cv_pred = y_pred + return + + def update_and_save_config(self): + """""" + Update and save config file. + """""" + self.config['num_classes'] = self.data['num_classes'] + self.config['target_cols'] = ','.join(self.data['target_cols']) + if self.config['task'] == 'multiclass': + self.config['multiclass_cnt'] = self.data['multiclass_cnt'] + + self.config['split_method'] = ( + f""{self.config['kfold']}fold_{self.config['split']}"" + ) + if self.save_path is not None: + if not os.path.exists(self.save_path): + logger.info('Create output directory: {}'.format(self.save_path)) + os.makedirs(self.save_path) + else: + logger.info( + 'Output directory already exists: {}'.format(self.save_path) + ) + logger.info( + 'Warning: Overwrite output directory: {}'.format(self.save_path) + ) + out_path = os.path.join(self.save_path, 'config.yaml') + self.yamlhandler.write_yaml(data=self.config, out_file_path=out_path) + return +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/predict.py",".py","5825","144","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os +import json + +import joblib +import numpy as np +from omegaconf import DictConfig, OmegaConf + +from .data import DataHub +from .models import NNModel +from .tasks import Trainer +from .utils import YamlHandler, logger + + +class MolPredict(object): + """"""A :class:`MolPredict` class is responsible for interface of predicting process of molecular data."""""" + + def __init__(self, load_model=None, cfg: DictConfig | None = None): + """""" + Initialize a :class:`MolPredict` class. + + :param load_model: str, default=None, path of model to load. + """""" + if cfg is not None: + cfg_dict = OmegaConf.to_container(cfg, resolve=True) + load_model = cfg_dict.get(""load_model"", load_model) + if not load_model: + raise ValueError(""load_model is empty"") + self.load_model = load_model + config_path = os.path.join(load_model, 'config.yaml') + self.config = YamlHandler(config_path).read_yaml() + self.config.target_cols = self.config.target_cols.split(',') + self.task = self.config.task + self.target_cols = self.config.target_cols + + def predict(self, data, save_path=None, metrics='none'): + """""" + Predict molecular data. + + :param data: str, list, numpy, pandas.Series, pandas.DataFrame, dict of atoms and coordinates, input data for prediction. + - str: path of csv file. + - list: list of smiles strings. + - numpy.ndarray: numpy array of data. + - pandas.Series: series of smiles strings. + - pandas.DataFrame: dataframe of data. + - dict: dict of atoms and coordinates, e.g. {'atoms': ['C', 'C', 'C'], 'coordinates': [[0, 0, 0], [0, 0, 1], [0, 0, 2]]} + :param save_path: str, default=None, path to save predict result. + :param metrics: str, default='none', metrics to evaluate model performance. + + currently support: + + - classification: auc, auprc, log_loss, acc, f1_score, mcc, precision, recall, cohen_kappa. + + - regression: mae, pearsonr, spearmanr, mse, r2. + + - multiclass: log_loss, acc. + + - multilabel_classification: auc, auprc, log_loss, acc, mcc. + + - multilabel_regression: mae, mse, r2. + + :return y_pred: numpy.ndarray, predict result. + """""" + self.save_path = save_path + self.config['sdf_save_path'] = save_path + if not metrics or metrics != 'none': + self.config.metrics = metrics + ## load test data + self.datahub = DataHub( + data=data, is_train=False, save_path=self.load_model, **self.config + ) + self.config.use_ddp = False + self.trainer = Trainer(save_path=self.load_model, **self.config) + self.model = NNModel(self.datahub.data, self.trainer, **self.config) + self.model.evaluate(self.trainer, self.load_model) + + y_pred = self.model.cv['test_pred'] + scalar = self.datahub.data['target_scaler'] + if scalar is not None: + y_pred = scalar.inverse_transform(y_pred) + + df = self.datahub.data['raw_data'].copy() + predict_cols = ['predict_' + col for col in self.target_cols] + if self.task == 'multiclass' and self.config.multiclass_cnt is not None: + prob_cols = ['prob_' + str(i) for i in range(self.config.multiclass_cnt)] + df[prob_cols] = y_pred + df[predict_cols] = np.argmax(y_pred, axis=1).reshape(-1, 1) + elif self.task in ['classification', 'multilabel_classification']: + threshold = joblib.load( + open(os.path.join(self.load_model, 'threshold.dat'), ""rb"") + ) + prob_cols = ['prob_' + col for col in self.target_cols] + df[prob_cols] = y_pred + df[predict_cols] = (y_pred > threshold).astype(int) + else: + prob_cols = predict_cols + df[predict_cols] = y_pred + if self.save_path: + os.makedirs(self.save_path, exist_ok=True) + if not (df[self.target_cols] == -1.0).all().all(): + metrics = self.trainer.metrics.cal_metric( + df[self.target_cols].values, df[prob_cols].values + ) + logger.info(""final predict metrics score: \n{}"".format(metrics)) + if self.save_path: + joblib.dump(metrics, os.path.join(self.save_path, 'test_metric.result')) + with open(os.path.join(self.save_path, 'test_metric.json'), 'w') as f: + json.dump(metrics, f) + else: + df.drop(self.target_cols, axis=1, inplace=True) + if self.save_path: + prefix = ( + data.split('/')[-1].split('.')[0] if isinstance(data, str) else 'test' + ) + self.save_predict(df, self.save_path, prefix) + logger.info(""pipeline finish!"") + + return y_pred + + def save_predict(self, data, dir, prefix): + """""" + Save predict result to csv file. + + :param data: pandas.DataFrame, predict result. + :param dir: str, directory to save predict result. + :param prefix: str, prefix of predict result file name. + """""" + run_id = 0 + if not os.path.exists(dir): + os.makedirs(dir) + else: + folders = [x for x in os.listdir(dir)] + while prefix + f'.predict.{run_id}' + '.csv' in folders: + run_id += 1 + name = prefix + f'.predict.{run_id}' + '.csv' + path = os.path.join(dir, name) + data.to_csv(path) + logger.info(""save predict result to {}"".format(path)) +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/__init__.py",".py","94","4","from .predict import MolPredict +from .predictor import UniMolRepr +from .train import MolTrain +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/predictor.py",".py","8074","201","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import numpy as np +import pandas as pd +import torch +from torch.utils.data import Dataset +from omegaconf import DictConfig, OmegaConf + +from .data import DataHub +from .models import UniMolModel, UniMolV2Model +from .tasks import Trainer + + +class MolDataset(Dataset): + """""" + A :class:`MolDataset` class is responsible for interface of molecular dataset. + """""" + + def __init__(self, data, label=None): + self.data = data + self.label = label if label is not None else np.zeros((len(data), 1)) + + def __getitem__(self, idx): + return self.data[idx], self.label[idx] + + def __len__(self): + return len(self.data) + + +class UniMolRepr(object): + """""" + A :class:`UniMolRepr` class is responsible for interface of molecular representation by unimol + """""" + + def __init__( + self, + cfg: DictConfig | None = None, + data_type='molecule', + batch_size=32, + remove_hs=False, + model_name='unimolv1', + model_size='84m', + smiles_col='SMILES', + use_cuda=True, + use_ddp=False, + use_gpu='all', + save_path=None, + pretrained_model_path=None, + pretrained_dict_path=None, + max_atoms=256, + **kwargs, + ): + """""" + Initialize a :class:`UniMolRepr` class. + + :param data_type: str, default='molecule', currently support molecule, oled, pocket. + :param batch_size: int, default=32, batch size for training. + :param remove_hs: bool, default=False, whether to remove hydrogens in molecular. + :param model_name: str, default='unimolv1', currently support unimolv1, unimolv2. + :param model_size: str, default='84m', model size of unimolv2. Avaliable: 84m, 164m, 310m, 570m, 1.1B. + :param smiles_col: str, default='SMILES', column name of SMILES. + :param use_cuda: bool, default=True, whether to use gpu. + :param use_ddp: bool, default=False, whether to use distributed data parallel. + :param use_gpu: str, default='all', which gpu to use. + :param save_path: str, default=None, path to save representation result. + :param pretrained_model_path: str, default=None, path to pretrained model. + :param pretrained_dict_path: str, default=None, path to pretrained model's dict file. + :param max_atoms: int, default=256, max atoms of molecular to be encode. + :param kwargs: other parameters. + """""" + if cfg is not None: + cfg_dict = OmegaConf.to_container(cfg, resolve=True) + data_type = cfg_dict.get('data_type', data_type) + batch_size = cfg_dict.get('batch_size', batch_size) + remove_hs = cfg_dict.get('remove_hs', remove_hs) + model_name = cfg_dict.get('model_name', model_name) + model_size = cfg_dict.get('model_size', model_size) + smiles_col = cfg_dict.get('smiles_col', smiles_col) + use_cuda = cfg_dict.get('use_cuda', use_cuda) + use_ddp = cfg_dict.get('use_ddp', use_ddp) + use_gpu = cfg_dict.get('use_gpu', use_gpu) + save_path = cfg_dict.get('save_path', save_path) + pretrained_model_path = cfg_dict.get( + 'pretrained_model_path', pretrained_model_path + ) + pretrained_dict_path = cfg_dict.get( + 'pretrained_dict_path', pretrained_dict_path + ) + max_atoms = cfg_dict.get('max_atoms', max_atoms) + + self.device = torch.device( + ""cuda:0"" if torch.cuda.is_available() and use_cuda else ""cpu"" + ) + if model_name == 'unimolv1': + self.model = UniMolModel( + output_dim=1, + data_type=data_type, + remove_hs=remove_hs, + pretrained_model_path=pretrained_model_path, + pretrained_dict_path=pretrained_dict_path, + ).to(self.device) + elif model_name == 'unimolv2': + self.model = UniMolV2Model( + output_dim=1, + model_size=model_size, + pretrained_model_path=pretrained_model_path, + ).to(self.device) + else: + raise ValueError('Unknown model name: {}'.format(model_name)) + self.model.eval() + self.params = { + 'data_type': data_type, + 'batch_size': batch_size, + 'remove_hs': remove_hs, + 'model_name': model_name, + 'model_size': model_size, + 'smiles_col': smiles_col, + 'use_cuda': use_cuda, + 'use_ddp': use_ddp, + 'use_gpu': use_gpu, + 'save_path': save_path, + 'pretrained_model_path': pretrained_model_path, + 'pretrained_dict_path': pretrained_dict_path, + 'max_atoms': max_atoms, + } + + def get_repr(self, data=None, return_atomic_reprs=False, return_tensor=False): + """""" + Get molecular representation by unimol. + + :param data: str, dict, list, numpy.ndarray, pandas.Series or pandas.Dataframe, default=None, input data for unimol. + + - str: smiles string or path to a smiles file. + + - dict: custom conformers, could take atoms and coordinates as input. + + - list: list of smiles strings. + + - numpy.ndarray: numpy.ndarray of smiles strings + + - pandas.Series: pandas Series of smiles strings. + + - pandas.DataFrame: pandas DataFrame of smiles strings or custom conformers. + + :param return_atomic_reprs: bool, default=False, whether to return atomic representations. + + :param return_tensor: bool, default=False, whether to return tensor representations. Only works when return_atomic_reprs=False. + + :return: + - if return_atomic_reprs=True: dict of molecular representation. + - if return_atomic_reprs=False and return_tensor=False: list of molecular representation. + - if return_atomic_reprs=False and return_tensor=True: tensor of molecular representation. + """""" + + if isinstance(data, str): + if data.endswith('.sdf') or data.endswith('.csv') or data.endswith('.pdb'): + # Datahub will process sdf and csv file. + pass + else: + # single smiles string. + data = [data] + elif isinstance(data, dict): + # custom conformers, should take atoms and coordinates as input. + if self.params['smiles_col'] not in data: + assert 'atoms' in data and 'coordinates' in data + else: + assert isinstance(data[self.params['smiles_col']][-1], str) + elif isinstance(data, list) or isinstance(data, np.ndarray) or isinstance(data, pd.Series): + # list of smiles strings. + assert isinstance(data[0], str) + elif isinstance(data, pd.DataFrame): + # pandas DataFrame of smiles strings. + if self.params['smiles_col'] not in data.columns: + assert ('atoms' in data.columns and 'coordinates' in data.columns) or 'ROMol' in data.columns + else: + assert isinstance(data[self.params['smiles_col']].iloc[0], str) + else: + raise ValueError('Unknown data type: {}'.format(type(data))) + + datahub = DataHub( + data=data, + task='repr', + is_train=False, + **self.params, + ) + dataset = MolDataset(datahub.data['unimol_input']) + self.trainer = Trainer(task='repr', **self.params) + repr_output = self.trainer.inference( + self.model, + model_name=self.params['model_name'], + return_repr=True, + return_atomic_reprs=return_atomic_reprs, + dataset=dataset, + return_tensor=return_tensor, + ) + return repr_output +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/weights/__init__.py",".py","75","2","from .weighthub import get_weight_dir, weight_download, weight_download_v2 +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/weights/weighthub.py",".py","4110","127","import os + +from ..utils import logger + +try: + from huggingface_hub import snapshot_download +except: + huggingface_hub_installed = False + + def snapshot_download(*args, **kwargs): + raise ImportError( + 'huggingface_hub is not installed. If weights are not avaliable, please install it by running: pip install huggingface_hub. Otherwise, please download the weights manually from https://huggingface.co/dptech/Uni-Mol-Models' + ) + + +DEFAULT_WEIGHT_DIR = os.path.dirname(os.path.abspath(__file__)) + +def get_weight_dir(): + """"""Return the directory where weights should be stored."""""" + return os.environ.get(""UNIMOL_WEIGHT_DIR"", DEFAULT_WEIGHT_DIR) + +HF_MIRROR = ""https://hf-mirror.com"" + +def _snapshot_download_with_fallback(**kwargs): + """"""Try downloading with the current HF_ENDPOINT and fall back to the mirror. + + The mirror is only tried when the user has not explicitly set HF_ENDPOINT + and the first attempt fails. + """""" + user_set = ""HF_ENDPOINT"" in os.environ + try: + return snapshot_download(**kwargs) + except Exception as e: + if user_set: + raise + logger.warning( + f""Download failed from Hugging Face: {e}. Retrying with {HF_MIRROR}"" + ) + os.environ[""HF_ENDPOINT""] = HF_MIRROR + return snapshot_download(**kwargs) + + +def log_weights_dir(): + """""" + Logs the directory where the weights are stored. + """""" + weight_dir = get_weight_dir() + + if 'UNIMOL_WEIGHT_DIR' in os.environ: + logger.warning( + f'Using custom weight directory from UNIMOL_WEIGHT_DIR: {weight_dir}' + ) + else: + logger.info(f'Weights will be downloaded to default directory: {weight_dir}') + + +def weight_download(pretrain, save_path, local_dir_use_symlinks=True): + """""" + Downloads the specified pretrained model weights. + + :param pretrain: (str), The name of the pretrained model to download. + :param save_path: (str), The directory where the weights should be saved. + :param local_dir_use_symlinks: (bool, optional), Whether to use symlinks for the local directory. Defaults to True. + """""" + log_weights_dir() + + if os.path.exists(os.path.join(save_path, pretrain)): + logger.info(f'{pretrain} exists in {save_path}') + return + + logger.info(f'Downloading {pretrain}') + _snapshot_download_with_fallback( + repo_id=""dptech/Uni-Mol-Models"", + local_dir=save_path, + allow_patterns=pretrain, + # local_dir_use_symlinks=local_dir_use_symlinks, + # max_workers=8 + ) + + +def weight_download_v2(pretrain, save_path, local_dir_use_symlinks=True): + """""" + Downloads the specified pretrained model weights. + + :param pretrain: (str), The name of the pretrained model to download. + :param save_path: (str), The directory where the weights should be saved. + :param local_dir_use_symlinks: (bool, optional), Whether to use symlinks for the local directory. Defaults to True. + """""" + log_weights_dir() + + if os.path.exists(os.path.join(save_path, pretrain)): + logger.info(f'{pretrain} exists in {save_path}') + return + + logger.info(f'Downloading {pretrain}') + _snapshot_download_with_fallback( + repo_id=""dptech/Uni-Mol2"", + local_dir=save_path, + allow_patterns=pretrain, + # local_dir_use_symlinks=local_dir_use_symlinks, + # max_workers=8 + ) + + +# Download all the weights when this script is run +def download_all_weights(local_dir_use_symlinks=False): + """""" + Downloads all available pretrained model weights to the WEIGHT_DIR. + + :param local_dir_use_symlinks: (bool, optional), Whether to use symlinks for the local directory. Defaults to False. + """""" + log_weights_dir() + weight_dir = get_weight_dir() + + logger.info(f'Downloading all weights to {weight_dir}') + _snapshot_download_with_fallback( + repo_id=""dptech/Uni-Mol-Models"", + local_dir=weight_dir, + allow_patterns='*', + # local_dir_use_symlinks=local_dir_use_symlinks, + # max_workers=8 + ) + + +if '__main__' == __name__: + download_all_weights() +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/cli/run_repr.py",".py","1014","37","import os +import hydra +import numpy as np +from omegaconf import DictConfig + +from ..predictor import UniMolRepr + + +@hydra.main(version_base=None, config_path=""../config"", config_name=""repr_config"") +def main(cfg: DictConfig): + data_path = cfg.get(""data_path"") + return_tensor = cfg.get(""return_tensor"", False) + return_atomic_reprs = cfg.get(""return_atomic_reprs"", False) + encoder = UniMolRepr(cfg=cfg) + reprs = encoder.get_repr( + data=data_path, + return_atomic_reprs=return_atomic_reprs, + return_tensor=return_tensor, + ) + save_dir = cfg.get(""save_path"") + + if not return_tensor and not return_atomic_reprs: + if save_dir: + os.makedirs(save_dir, exist_ok=True) + np.save(os.path.join(save_dir, ""repr.npy""), reprs) + np.savetxt( + os.path.join(save_dir, ""repr.csv""), np.asarray(reprs), delimiter="","" + ) + else: + print(reprs) + else: + print(reprs) + + +if __name__ == ""__main__"": + main() +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/cli/__init__.py",".py","0","0","","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/cli/run_predict.py",".py","378","16","import hydra +from omegaconf import DictConfig + +from ..predict import MolPredict + + +@hydra.main(version_base=None, config_path=""../config"", config_name=""predict_config"") +def main(cfg: DictConfig): + data_path = cfg.get(""data_path"") + predictor = MolPredict(cfg=cfg) + predictor.predict(data=data_path, save_path=cfg.get(""save_path"")) + + +if __name__ == ""__main__"": + main() +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/cli/run_train.py",".py","410","18","import hydra +from omegaconf import DictConfig + +from ..train import MolTrain + + +@hydra.main(version_base=None, config_path=""../config"", config_name=""train_config"") +def main(cfg: DictConfig): + data_path = cfg.get(""train_path"") + if not data_path: + raise ValueError(""train_path must be specified"") + trainer = MolTrain(cfg=cfg) + trainer.fit(data=data_path) + + +if __name__ == ""__main__"": + main() +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/cli/run_pretrain.py",".py","11093","276","import os +import random +import logging +import shutil +import time + +import hydra +import numpy as np +import torch +import torch.distributed as dist +from omegaconf import DictConfig + +from unimol_tools.pretrain import ( + LMDBDataset, + UniMolDataset, + UniMolLoss, + UniMolModel, + UniMolPretrainTrainer, + build_dictionary, + preprocess_dataset, + compute_lmdb_dist_stats, + count_input_data, + count_lmdb_entries, +) +from unimol_tools.data.dictionary import Dictionary + +logger = logging.getLogger(__name__) + + +def load_or_compute_dist_stats(lmdb_path, rank, num_workers=1): + """"""Load cached distance statistics or compute them on rank 0."""""" + stats_file = os.path.join(os.path.dirname(lmdb_path), ""dist_stats.npy"") + if os.path.exists(stats_file): + dist_mean, dist_std = np.load(stats_file) + return float(dist_mean), float(dist_std) + if rank == 0: + dist_mean, dist_std = compute_lmdb_dist_stats(lmdb_path, num_workers=num_workers) + np.save(stats_file, np.array([dist_mean, dist_std], dtype=np.float32)) + else: + while not os.path.exists(stats_file): + time.sleep(1) + dist_mean, dist_std = np.load(stats_file) + return float(dist_mean), float(dist_std) + + +def load_or_build_dictionary(lmdb_path, rank, dict_path=None, num_workers=1): + """"""Load existing dictionary file or build it on rank 0."""""" + if dict_path is None: + dict_path = os.path.join(os.path.dirname(lmdb_path), ""dictionary.txt"") + if os.path.exists(dict_path): + return Dictionary.load(dict_path), dict_path + if rank == 0: + dictionary = build_dictionary(lmdb_path, save_path=dict_path, num_workers=num_workers) + else: + while not os.path.exists(dict_path): + time.sleep(1) + dictionary = Dictionary.load(dict_path) + return dictionary, dict_path + + +class MolPretrain: + def __init__(self, cfg: DictConfig): + # Read configuration + self.config = cfg + # Ranks are provided by torchrun + self.local_rank = int(os.environ.get(""LOCAL_RANK"", 0)) + self.rank = int(os.environ.get(""RANK"", 0)) + seed = getattr(self.config.training, 'seed', 42) + self.set_seed(seed) + + # Preprocess dataset if necessary + ds_cfg = self.config.dataset + train_lmdb = ds_cfg.train_path + val_lmdb = ds_cfg.valid_path + self.dist_mean = None + self.dist_std = None + stats_workers = ds_cfg.get(""stats_workers"", 1) + if ds_cfg.data_type != 'lmdb' and not ds_cfg.train_path.endswith('.lmdb'): + lmdb_path = os.path.splitext(ds_cfg.train_path)[0] + '.lmdb' + expected_cnt = count_input_data( + ds_cfg.train_path, ds_cfg.data_type, ds_cfg.smiles_column + ) + stats_file = os.path.join(os.path.dirname(lmdb_path), ""dist_stats.npy"") + if self.rank == 0: + regenerate = True + if os.path.exists(lmdb_path): + lmdb_cnt = count_lmdb_entries(lmdb_path) + if lmdb_cnt == expected_cnt: + logger.info( + f""Found existing training LMDB {lmdb_path} with {lmdb_cnt} molecules"" + ) + regenerate = False + else: + logger.warning( + f""Existing LMDB {lmdb_path} has {lmdb_cnt} molecules but {expected_cnt} are expected; regenerating"" + ) + if regenerate: + lmdb_path, self.dist_mean, self.dist_std = preprocess_dataset( + ds_cfg.train_path, + lmdb_path, + data_type=ds_cfg.data_type, + smiles_col=ds_cfg.smiles_column, + num_conf=ds_cfg.num_conformers, + remove_hs=ds_cfg.remove_hydrogen, + num_workers=ds_cfg.preprocess_workers, + ) + np.save( + stats_file, + np.array([self.dist_mean, self.dist_std], dtype=np.float32), + ) + train_lmdb = lmdb_path + else: + while True: + if os.path.exists(lmdb_path): + lmdb_cnt = count_lmdb_entries(lmdb_path) + if lmdb_cnt == expected_cnt and os.path.exists(stats_file): + break + time.sleep(1) + train_lmdb = lmdb_path + self.dist_mean, self.dist_std = load_or_compute_dist_stats( + train_lmdb, self.rank, num_workers=stats_workers + ) + + if ds_cfg.valid_path: + val_lmdb = os.path.splitext(ds_cfg.valid_path)[0] + '.lmdb' + expected_val_cnt = count_input_data( + ds_cfg.valid_path, ds_cfg.data_type, ds_cfg.smiles_column + ) + if self.rank == 0: + regenerate_val = True + if os.path.exists(val_lmdb): + val_cnt = count_lmdb_entries(val_lmdb) + if val_cnt == expected_val_cnt: + logger.info( + f""Found existing validation LMDB {val_lmdb} with {val_cnt} molecules"" + ) + regenerate_val = False + else: + logger.warning( + f""Existing validation LMDB {val_lmdb} has {val_cnt} molecules but {expected_val_cnt} are expected; regenerating"" + ) + if regenerate_val: + preprocess_dataset( + ds_cfg.valid_path, + val_lmdb, + data_type=ds_cfg.data_type, + smiles_col=ds_cfg.smiles_column, + num_conf=ds_cfg.num_conformers, + remove_hs=ds_cfg.remove_hydrogen, + num_workers=ds_cfg.preprocess_workers, + ) + else: + while True: + if os.path.exists(val_lmdb): + val_cnt = count_lmdb_entries(val_lmdb) + if val_cnt == expected_val_cnt: + break + time.sleep(1) + else: + if train_lmdb: + self.dist_mean, self.dist_std = load_or_compute_dist_stats( + train_lmdb, self.rank, num_workers=stats_workers + ) + + # Build dictionary + dict_path = ds_cfg.get('dict_path', None) + if dict_path: + self.dictionary = Dictionary.load(dict_path) + self.dict_path = dict_path + logger.info(f""Loaded dictionary from {dict_path}"") + else: + self.dictionary, self.dict_path = load_or_build_dictionary( + train_lmdb, self.rank, num_workers=stats_workers + ) + if self.rank == 0: + logger.info(""Built dictionary from training LMDB"") + else: + logger.info(f""Loaded dictionary from {self.dict_path}"") + + # Build dataset + logger.info(f""Loading LMDB dataset from {train_lmdb}"") + lmdb_dataset = LMDBDataset(train_lmdb) + self.dataset = UniMolDataset( + lmdb_dataset, + self.dictionary, + remove_hs=ds_cfg.remove_hydrogen, + max_atoms=ds_cfg.max_atoms, + seed=seed, + noise_type=ds_cfg.noise_type, + noise=ds_cfg.noise, + mask_prob=ds_cfg.mask_prob, + leave_unmasked_prob=ds_cfg.leave_unmasked_prob, + random_token_prob=ds_cfg.random_token_prob, + sample_conformer=True, + add_2d=ds_cfg.add_2d, + ) + + if val_lmdb: + logger.info(f""Loading validation LMDB dataset from {val_lmdb}"") + val_lmdb_dataset = LMDBDataset(val_lmdb) + self.valid_dataset = UniMolDataset( + val_lmdb_dataset, + self.dictionary, + remove_hs=ds_cfg.remove_hydrogen, + max_atoms=ds_cfg.max_atoms, + seed=seed, + noise_type=ds_cfg.noise_type, + noise=ds_cfg.noise, + mask_prob=ds_cfg.mask_prob, + leave_unmasked_prob=ds_cfg.leave_unmasked_prob, + random_token_prob=ds_cfg.random_token_prob, + sample_conformer=True, + add_2d=ds_cfg.add_2d, + ) + else: + self.valid_dataset = None + + def pretrain(self): + # Build model + model = UniMolModel(self.config.model, dictionary=self.dictionary) + # Build loss function + loss_fn = UniMolLoss( + self.dictionary, + masked_token_loss=self.config.model.masked_token_loss, + masked_coord_loss=self.config.model.masked_coord_loss, + masked_dist_loss=self.config.model.masked_dist_loss, + x_norm_loss=self.config.model.x_norm_loss, + delta_pair_repr_norm_loss=self.config.model.delta_pair_repr_norm_loss, + dist_mean=self.dist_mean, + dist_std=self.dist_std, + ) + # Build trainer + trainer = UniMolPretrainTrainer( + model, + self.dataset, + loss_fn, + self.config.training, + local_rank=self.local_rank, + resume=self.config.training.get('resume', None), + valid_dataset=self.valid_dataset, + ) + if self.rank == 0 and getattr(self, 'dict_path', None): + try: + dst_path = os.path.join(trainer.ckpt_dir, os.path.basename(self.dict_path)) + shutil.copy(self.dict_path, dst_path) + logger.info(f""Copied dictionary file to {dst_path}"") + except Exception as e: + logger.warning(f""Failed to copy dictionary file: {e}"") + logger.info(""Starting pretraining"") + trainer.train(max_steps=self.config.training.total_steps) + logger.info(""Training finished. Checkpoints saved under the run directory."") + + def set_seed(self, seed): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + +@hydra.main(version_base=None, config_path=None, config_name=""pretrain_config"") +def main(cfg: DictConfig): + rank = int(os.environ.get(""RANK"", 0)) + if rank != 0: + logging.disable(logging.WARNING) + try: + task = MolPretrain(cfg) + task.pretrain() + finally: + if dist.is_available() and dist.is_initialized(): + dist.destroy_process_group() + +if __name__ == ""__main__"": + main()","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/utils/metrics.py",".py","12546","353","import copy +import os + +import numpy as np +import pandas as pd +import torch +from scipy.stats import pearsonr, spearmanr +from sklearn.metrics import ( + accuracy_score, + average_precision_score, + cohen_kappa_score, + f1_score, + log_loss, + matthews_corrcoef, + mean_absolute_error, + mean_squared_error, + precision_score, + r2_score, + recall_score, + roc_auc_score, +) + +from .base_logger import logger + + +def cal_nan_metric(y_true, y_pred, nan_value=None, metric_func=None): + if y_true.shape != y_pred.shape: + raise ValueError('y_ture and y_pred must have same shape') + + if isinstance(y_true, pd.DataFrame): + y_true = y_true.to_numpy() + + if isinstance(y_pred, pd.DataFrame): + y_pred = y_pred.to_numpy() + + if not np.issubdtype(y_true.dtype, np.floating): + y_true = y_true.astype(np.float64) + + mask = ~np.isnan(y_true) + if nan_value is not None: + mask = mask & (y_true != nan_value) + + sz = y_true.shape[1] + result = [] + for i in range(sz): + _mask = mask[:, i] + if not (~_mask).all(): + result.append(metric_func(y_true[:, i][_mask], y_pred[:, i][_mask])) + return np.mean(result) + + +def multi_acc(y_true, y_pred): + y_true = y_true.flatten() + y_pred_idx = np.argmax(y_pred, axis=1) + return np.mean(y_true == y_pred_idx) + + +def log_loss_with_label(y_true, y_pred, labels=None): + if labels is None: + return log_loss(y_true, y_pred) + else: + return log_loss(y_true, y_pred, labels=labels) + + +def reg_preasonr(y_true, y_pred): + return pearsonr(y_true, y_pred)[0] + + +def reg_spearmanr(y_true, y_pred): + return spearmanr(y_true, y_pred)[0] + + +# metric_func, is_increase, value_type +METRICS_REGISTER = { + 'regression': { + ""mae"": [mean_absolute_error, False, 'float'], + ""pearsonr"": [reg_preasonr, True, 'float'], + ""spearmanr"": [reg_spearmanr, True, 'float'], + ""mse"": [mean_squared_error, False, 'float'], + ""r2"": [r2_score, True, 'float'], + }, + 'classification': { + ""auroc"": [roc_auc_score, True, 'float'], + ""auc"": [roc_auc_score, True, 'float'], + ""auprc"": [average_precision_score, True, 'float'], + ""log_loss"": [log_loss, False, 'float'], + ""acc"": [accuracy_score, True, 'int'], + ""f1_score"": [f1_score, True, 'int'], + ""mcc"": [matthews_corrcoef, True, 'int'], + ""precision"": [precision_score, True, 'int'], + ""recall"": [recall_score, True, 'int'], + ""cohen_kappa"": [cohen_kappa_score, True, 'int'], + }, + 'multiclass': { + ""log_loss"": [log_loss_with_label, False, 'float'], + ""acc"": [multi_acc, True, 'int'], + }, + 'multilabel_classification': { + ""auroc"": [roc_auc_score, True, 'float'], + ""auc"": [roc_auc_score, True, 'float'], + ""auprc"": [average_precision_score, True, 'float'], + ""log_loss"": [log_loss_with_label, False, 'float'], + ""acc"": [accuracy_score, True, 'int'], + ""mcc"": [matthews_corrcoef, True, 'int'], + }, + 'multilabel_regression': { + ""mae"": [mean_absolute_error, False, 'float'], + ""mse"": [mean_squared_error, False, 'float'], + ""r2"": [r2_score, True, 'float'], + }, +} + +DEFAULT_METRICS = { + 'regression': ['mse', 'mae', 'r2', 'spearmanr', 'pearsonr'], + 'classification': [ + 'log_loss', + 'auc', + 'f1_score', + 'mcc', + 'acc', + 'precision', + 'recall', + ], + 'multiclass': ['log_loss', 'acc'], + ""multilabel_classification"": ['log_loss', 'auc', 'auprc'], + ""multilabel_regression"": ['mse', 'mae', 'r2'], +} + + +class Metrics(object): + """""" + Class for calculating metrics for different tasks. + + :param task: The task type. Supported tasks are 'regression', 'multilabel_regression', + 'classification', 'multilabel_classification', and 'multiclass'. + :param metrics_str: Comma-separated string of metric names. If provided, only the specified metrics will be calculated. If not provided or an empty string, default metrics for the task will be used. + """""" + + def __init__(self, task=None, metrics_str=None, **params): + self.task = task + self.threshold = np.arange(0, 1.0, 0.1) + self.metric_dict = self._init_metrics(self.task, metrics_str, **params) + self.METRICS_REGISTER = METRICS_REGISTER[task] + + def _init_metrics(self, task, metrics_str, **params): + if task not in METRICS_REGISTER: + raise ValueError('Unknown task: {}'.format(self.task)) + if ( + not isinstance(metrics_str, str) + or metrics_str == '' + or metrics_str == 'none' + ): + metric_dict = { + key: METRICS_REGISTER[task][key] for key in DEFAULT_METRICS[task] + } + else: + for key in metrics_str.split(','): + if key not in METRICS_REGISTER[task]: + raise ValueError('Unknown metric: {}'.format(key)) + + priority_metric_list = metrics_str.split(',') + metric_list = priority_metric_list + [ + key for key in METRICS_REGISTER[task] if key not in priority_metric_list + ] + metric_dict = {key: METRICS_REGISTER[task][key] for key in metric_list} + + return metric_dict + + def cal_classification_metric(self, label, predict, nan_value=-1.0, threshold=None): + """""" + :param label: the labels of the dataset. + :param predict: the predict values of the model. + """""" + res_dict = {} + for metric_type, metric_value in self.metric_dict.items(): + metric, _, value_type = metric_value + + def nan_metric(label, predict): + return cal_nan_metric(label, predict, nan_value, metric) + + if value_type == 'float': + res_dict[metric_type] = nan_metric( + label.astype(int), predict.astype(np.float32) + ) + elif value_type == 'int': + thre = 0.5 if threshold is None else threshold + res_dict[metric_type] = nan_metric( + label.astype(int), (predict > thre).astype(int) + ) + + # TO DO : add more metrics by grid search threshold + + return res_dict + + def cal_reg_metric(self, label, predict, nan_value=-1.0): + """""" + :param label: the labels of the dataset. + :param predict: the predict values of the model. + """""" + res_dict = {} + for metric_type, metric_value in self.metric_dict.items(): + metric, _, _ = metric_value + + def nan_metric(label, predict): + return cal_nan_metric(label, predict, nan_value, metric) + + res_dict[metric_type] = nan_metric(label, predict) + + return res_dict + + def cal_multiclass_metric(self, label, predict, nan_value=-1.0, label_cnt=-1): + """""" + :param label: the labels of the dataset. + :param predict: the predict values of the model. + """""" + res_dict = {} + for metric_type, metric_value in self.metric_dict.items(): + metric, _, _ = metric_value + if metric_type == 'log_loss' and label_cnt is not None: + labels = list(range(label_cnt)) + res_dict[metric_type] = metric(label, predict, labels) + else: + res_dict[metric_type] = metric(label, predict) + + return res_dict + + def cal_metric(self, label, predict, nan_value=-1.0, threshold=0.5, label_cnt=None): + if self.task in ['regression', 'multilabel_regression']: + return self.cal_reg_metric(label, predict, nan_value) + elif self.task in ['classification', 'multilabel_classification']: + return self.cal_classification_metric(label, predict, nan_value) + elif self.task in ['multiclass']: + return self.cal_multiclass_metric(label, predict, nan_value, label_cnt) + else: + raise ValueError(""We will add more tasks soon"") + + def _early_stop_choice( + self, + wait, + min_score, + metric_score, + max_score, + model, + dump_dir, + fold, + patience, + epoch, + ): + score = list(metric_score.values())[0] + judge_metric = list(metric_score.keys())[0] + is_increase = METRICS_REGISTER[self.task][judge_metric][1] + if is_increase: + is_early_stop, max_score, wait = self._judge_early_stop_increase( + wait, score, max_score, model, dump_dir, fold, patience, epoch + ) + else: + is_early_stop, min_score, wait = self._judge_early_stop_decrease( + wait, score, min_score, model, dump_dir, fold, patience, epoch + ) + return is_early_stop, min_score, wait, max_score + + def _judge_early_stop_decrease( + self, wait, score, min_score, model, dump_dir, fold, patience, epoch + ): + is_early_stop = False + if score <= min_score: + min_score = score + wait = 0 + info = {'model_state_dict': model.state_dict()} + os.makedirs(dump_dir, exist_ok=True) + torch.save(info, os.path.join(dump_dir, f'model_{fold}.pth')) + elif score >= min_score: + wait += 1 + if wait == patience: + logger.warning(f'Early stopping at epoch: {epoch+1}') + is_early_stop = True + return is_early_stop, min_score, wait + + def _judge_early_stop_increase( + self, wait, score, max_score, model, dump_dir, fold, patience, epoch + ): + is_early_stop = False + if score >= max_score: + max_score = score + wait = 0 + info = {'model_state_dict': model.state_dict()} + os.makedirs(dump_dir, exist_ok=True) + torch.save(info, os.path.join(dump_dir, f'model_{fold}.pth')) + elif score <= max_score: + wait += 1 + if wait == patience: + logger.warning(f'Early stopping at epoch: {epoch+1}') + is_early_stop = True + return is_early_stop, max_score, wait + + def calculate_single_classification_threshold( + self, target, pred, metrics_key=None, step=20 + ): + data = copy.deepcopy(pred) + range_min = np.min(data).item() + range_max = np.max(data).item() + + for metric_type, metric_value in self.metric_dict.items(): + metric, is_increase, value_type = metric_value + if value_type == 'int': + metrics_key = metric_value + break + # default threshold metrics + if metrics_key is None: + metrics_key = METRICS_REGISTER['classification']['f1_score'] + logger.info(""metrics for threshold: {0}"".format(metrics_key[0].__name__)) + metrics = metrics_key[0] + if metrics_key[1]: + # increase metric + best_metric = float('-inf') + best_threshold = 0.5 + for threshold in np.linspace(range_min, range_max, step): + pred_label = np.zeros_like(pred) + pred_label[pred > threshold] = 1 + # print (""threshold: "", threshold, metric(target, pred_label)) + if metric(target, pred_label) > best_metric: + best_metric = metric(target, pred_label) + best_threshold = threshold + logger.info( + ""best threshold: {0}, metrics: {1}"".format(best_threshold, best_metric) + ) + else: + # increase metric + best_metric = float('inf') + best_threshold = 0.5 + for threshold in np.linspace(range_min, range_max, step): + pred_label = np.zeros_like(pred) + pred_label[pred > threshold] = 1 + if metric(target, pred_label) < best_metric: + best_metric = metric(target, pred_label) + best_threshold = threshold + logger.info( + ""best threshold: {0}, metrics: {1}"".format(best_threshold, best_metric) + ) + + return best_threshold + + def calculate_classification_threshold(self, target, pred): + threshold = np.zeros(target.shape[1]) + for idx in range(target.shape[1]): + threshold[idx] = self.calculate_single_classification_threshold( + target[:, idx].reshape(-1, 1), + pred[:, idx].reshape(-1, 1), + metrics_key=None, + step=20, + ) + return threshold +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/utils/config_handler.py",".py","2078","67","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os + +import yaml +from addict import Dict + +from .base_logger import logger + + +class YamlHandler: + '''A class to read and write the yaml file''' + + def __init__(self, file_path): + """""" + A custom logger class that provides logging functionality to console and file. + + :param file_path: (str) The yaml file path of the config. + """""" + if not os.path.exists(file_path): + raise FileNotFoundError(file_path) + self.file_path = file_path + + def read_yaml(self, encoding='utf-8'): + """"""read yaml file and convert to easydict + + :param encoding: (str) encoding method uses utf-8 by default + :return: Dict (addict), the usage of Dict is the same as dict + """""" + with open(self.file_path, encoding=encoding) as f: + return Dict(yaml.load(f.read(), Loader=yaml.FullLoader)) + + def write_yaml(self, data, out_file_path, encoding='utf-8'): + """"""write dict or easydict to yaml file(auto write to self.file_path) + + :param data: (dict or Dict(addict)) dict containing the contents of the yaml file + """""" + with open(out_file_path, encoding=encoding, mode='w') as f: + return yaml.dump( + addict2dict(data) if isinstance(data, Dict) else data, + stream=f, + allow_unicode=True, + ) + + +def addict2dict(addict_obj): + '''convert addict to dict + + :param addict_obj: (Dict(addict)) the addict obj that you want to convert to dict + + :return: (Dict) converted result + ''' + dict_obj = {} + for key, vals in addict_obj.items(): + dict_obj[key] = addict2dict(vals) if isinstance(vals, Dict) else vals + return dict_obj + + +if __name__ == '__main__': + yaml_handler = YamlHandler('../config/default.yaml') + config = yaml_handler.read_yaml() + print(config.Modelhub) +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/utils/__init__.py",".py","121","5","from .base_logger import logger +from .config_handler import YamlHandler +from .metrics import Metrics +from .util import * +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/utils/util.py",".py","3801","119","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from hashlib import md5 + + +def pad_1d_tokens( + values, + pad_idx, + left_pad=False, + pad_to_length=None, + pad_to_multiple=1, +): + """""" + padding one dimension tokens inputs. + + :param values: A list of 1d tensors. + :param pad_idx: The padding index. + :param left_pad: Whether to left pad the tensors. Defaults to False. + :param pad_to_length: The desired length of the padded tensors. Defaults to None. + :param pad_to_multiple: The multiple to pad the tensors to. Defaults to 1. + + :return: A padded 1d tensor as a torch.Tensor. + + """""" + size = max(v.size(0) for v in values) + size = size if pad_to_length is None else max(size, pad_to_length) + if pad_to_multiple != 1 and size % pad_to_multiple != 0: + size = int(((size - 0.1) // pad_to_multiple + 1) * pad_to_multiple) + res = values[0].new(len(values), size).fill_(pad_idx) + + def copy_tensor(src, dst): + assert dst.numel() == src.numel() + dst.copy_(src) + + for i, v in enumerate(values): + copy_tensor(v, res[i][size - len(v) :] if left_pad else res[i][: len(v)]) + return res + + +def pad_2d( + values, + pad_idx, + dim=1, + left_pad=False, + pad_to_length=None, + pad_to_multiple=1, +): + """""" + padding two dimension tensor inputs. + + :param values: A list of 2d tensors. + :param pad_idx: The padding index. + :param left_pad: Whether to pad on the left side. Defaults to False. + :param pad_to_length: The length to pad the tensors to. If None, the maximum length in the list + is used. Defaults to None. + :param pad_to_multiple: The multiple to pad the tensors to. Defaults to 1. + + :return: A padded 2d tensor as a torch.Tensor. + """""" + size = max(v.size(0) for v in values) + size = size if pad_to_length is None else max(size, pad_to_length) + if pad_to_multiple != 1 and size % pad_to_multiple != 0: + size = int(((size - 0.1) // pad_to_multiple + 1) * pad_to_multiple) + if dim == 1: + res = values[0].new(len(values), size, size).fill_(pad_idx) + else: + res = values[0].new(len(values), size, size, dim).fill_(pad_idx) + + def copy_tensor(src, dst): + assert dst.numel() == src.numel() + dst.copy_(src) + + for i, v in enumerate(values): + copy_tensor( + v, + ( + res[i][size - len(v) :, size - len(v) :] + if left_pad + else res[i][: len(v), : len(v)] + ), + ) + return res + + +def pad_coords( + values, + pad_idx, + dim=3, + left_pad=False, + pad_to_length=None, + pad_to_multiple=1, +): + """""" + padding two dimension tensor coords which the third dimension is 3. + + :param values: A list of 1d tensors. + :param pad_idx: The value used for padding. + :param left_pad: Whether to pad on the left side. Defaults to False. + :param pad_to_length: The desired length of the padded tensor. Defaults to None. + :param pad_to_multiple: The multiple to pad the tensor to. Defaults to 1. + + :return: A padded 2d coordinate tensor as a torch.Tensor. + """""" + size = max(v.size(0) for v in values) + size = size if pad_to_length is None else max(size, pad_to_length) + if pad_to_multiple != 1 and size % pad_to_multiple != 0: + size = int(((size - 0.1) // pad_to_multiple + 1) * pad_to_multiple) + res = values[0].new(len(values), size, dim).fill_(pad_idx) + + def copy_tensor(src, dst): + assert dst.numel() == src.numel() + dst.copy_(src) + + for i, v in enumerate(values): + copy_tensor(v, res[i][size - len(v) :, :] if left_pad else res[i][: len(v), :]) + return res +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/utils/dynamic_loss_scaler.py",".py","2684","74","from typing import Optional + +import torch + + +class DynamicLossScaler: + """"""Simplified dynamic loss scaler mirroring Uni-Core's implementation."""""" + + def __init__( + self, + init_scale: float = 2.0 ** 15, + scale_factor: float = 2.0, + scale_window: int = 2000, + tolerance: float = 0.0, + threshold: Optional[float] = None, + min_loss_scale: float = 1e-4, + ) -> None: + self.loss_scale = init_scale + self.scale_factor = scale_factor + self.scale_window = scale_window + self.tolerance = tolerance + self.threshold = threshold + self.min_loss_scale = min_loss_scale + + self._iter = 0 + self._last_overflow_iter = -1 + self._last_rescale_iter = -1 + self._overflows_since_rescale = 0 + + def scale(self, loss: torch.Tensor) -> torch.Tensor: + return loss * self.loss_scale + + def unscale_(self, params) -> None: + inv_scale = 1.0 / self.loss_scale + for p in params: + if p.grad is not None: + p.grad.data.mul_(inv_scale) + + def update(self) -> None: + if (self._iter - self._last_overflow_iter) % self.scale_window == 0: + self.loss_scale *= self.scale_factor + self._last_rescale_iter = self._iter + self._iter += 1 + + def _decrease_loss_scale(self) -> None: + self.loss_scale /= self.scale_factor + if self.threshold is not None: + self.loss_scale = max(self.loss_scale, self.threshold) + + def check_overflow(self, grad_norm: float) -> None: + if grad_norm == float(""inf"") or grad_norm != grad_norm: + prev_scale = self.loss_scale + iter_since_rescale = self._iter - self._last_rescale_iter + + self._last_overflow_iter = self._iter + self._overflows_since_rescale += 1 + pct_overflow = self._overflows_since_rescale / float(iter_since_rescale) + if pct_overflow >= self.tolerance: + self._decrease_loss_scale() + self._last_rescale_iter = self._iter + self._overflows_since_rescale = 0 + + if self.loss_scale <= self.min_loss_scale: + self.loss_scale = prev_scale + raise FloatingPointError( + ( + ""Minimum loss scale reached ({}). Your loss is probably exploding. "" + ""Try lowering the learning rate, using gradient clipping or "" + ""increasing the batch size."" + ).format(self.min_loss_scale) + ) + + self._iter += 1 + raise OverflowError(""setting loss scale to: "" + str(self.loss_scale))","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/utils/base_logger.py",".py","3827","114","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import datetime +import logging +import os +import sys +import threading +from logging.handlers import TimedRotatingFileHandler + +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) + + +class PackagePathFilter(logging.Filter): + """"""A custom logging filter for adding the relative path to the log record."""""" + + def filter(self, record): + """"""add relative path to record"""""" + pathname = record.pathname + record.relativepath = None + abs_sys_paths = map(os.path.abspath, sys.path) + for path in sorted(abs_sys_paths, key=len, reverse=True): # longer paths first + if not path.endswith(os.sep): + path += os.sep + if pathname.startswith(path): + record.relativepath = os.path.relpath(pathname, path) + break + return True + + +class Logger(object): + """"""A custom logger class that provides logging functionality to console and file."""""" + + _instance = None + _lock = threading.Lock() + + DATE_FORMAT = ""%Y-%m-%d %H:%M:%S"" + LOG_FORMAT = ""%(asctime)s | %(relativepath)s | %(lineno)s | %(levelname)s | %(name)s | %(message)s"" + + def __new__(cls, *args, **kwargs): + if not cls._instance: + with cls._lock: + if not cls._instance: + cls._instance = super(Logger, cls).__new__(cls) + return cls._instance + + def __init__(self, logger_name='None'): + """""" + :param logger_name: (str) The name of the logger (default: 'None') + """""" + self.logger = logging.getLogger(logger_name) + logging.root.setLevel(logging.NOTSET) + self.log_file_name = 'unimol_tools_{0}.log'.format( + datetime.datetime.now().strftime(""%Y-%m-%d-%H-%M-%S"") + ) + + cwd_path = os.path.abspath(os.getcwd()) + self.log_path = os.path.join(cwd_path, ""logs"") + + os.makedirs(self.log_path, exist_ok=True) + self.backup_count = 5 + + self.console_output_level = 'INFO' + self.file_output_level = 'INFO' + + self.formatter = logging.Formatter(self.LOG_FORMAT, self.DATE_FORMAT) + + def get_logger(self): + """""" + Get the logger object. + + :return: logging.Logger - a logger object. + + """""" + if not self.logger.handlers: + console_handler = logging.StreamHandler() + console_handler.setFormatter(self.formatter) + console_handler.setLevel(self.console_output_level) + console_handler.addFilter(PackagePathFilter()) + self.logger.addHandler(console_handler) + + file_handler = TimedRotatingFileHandler( + filename=os.path.join(self.log_path, self.log_file_name), + when='D', + interval=1, + backupCount=self.backup_count, + delay=True, + encoding='utf-8', + ) + file_handler.setFormatter(self.formatter) + file_handler.setLevel(self.file_output_level) + self.logger.addHandler(file_handler) + return self.logger + + +# add highlight formatter to logger +class HighlightFormatter(logging.Formatter): + def format(self, record): + if record.levelno == logging.WARNING: + record.msg = ""\033[93m{}\033[0m"".format(record.msg) # yellow highlight + return super().format(record) + + +logger = Logger('Uni-Mol Tools').get_logger() +logger.setLevel(logging.INFO) + +# highlight warning messages in console +for handler in logger.handlers: + if isinstance(handler, logging.StreamHandler): + handler.setFormatter(HighlightFormatter(Logger.LOG_FORMAT, Logger.DATE_FORMAT)) +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/tasks/trainer.py",".py","45586","1172","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os +import time +from functools import partial + +import numpy as np +import torch +import torch.distributed as dist +import torch.multiprocessing as mp +import torch.nn as nn +from torch.nn.parallel import DistributedDataParallel +from torch.nn.utils import clip_grad_norm_ +from torch.optim import Adam +from torch.optim.lr_scheduler import LambdaLR +from torch.utils.data import DataLoader as TorchDataLoader +from torch.utils.data.distributed import DistributedSampler +from tqdm import tqdm + +# from transformers.optimization import get_linear_schedule_with_warmup +from ..utils import Metrics, logger + + +class Trainer(object): + """"""A :class:`Trainer` class is responsible for initializing the model, and managing its training, validation, and testing phases."""""" + + def __init__(self, save_path=None, **params): + """""" + :param save_path: Path for saving the training outputs. Defaults to None. + :param params: Additional parameters for training. + """""" + self.save_path = save_path + self.task = params.get('task', None) + + if self.task != 'repr': + self.metrics_str = params['metrics'] + self.metrics = Metrics(self.task, self.metrics_str) + self._init_trainer(**params) + + def _init_trainer(self, **params): + """""" + Initializing the trainer class to train model. + + :param params: Containing training arguments. + """""" + ### init common params ### + self.split_method = params.get('split_method', '5fold_random') + self.split_seed = params.get('split_seed', 42) + self.seed = params.get('seed', 42) + self.set_seed(self.seed) + self.logger_level = int(params.get('logger_level', 1)) + ### init NN trainer params ### + self.learning_rate = float(params.get('learning_rate', 1e-4)) + self.batch_size = params.get('batch_size', 32) + self.max_epochs = params.get('epochs', 50) + self.warmup_ratio = params.get('warmup_ratio', 0.1) + self.patience = params.get('patience', 10) + self.max_norm = params.get('max_norm', 1.0) + self._init_dist(params) + + def _init_dist(self, params): + self.cuda = params.get('use_cuda', True) + self.amp = params.get('use_amp', True) + self.ddp = params.get('use_ddp', False) + self.gpu = params.get('use_gpu', ""all"") + + if torch.cuda.is_available() and self.cuda: + if self.amp: + self.scaler = torch.amp.GradScaler(""cuda"") + else: + self.scaler = None + self.device = torch.device(""cuda"") + world_size = torch.cuda.device_count() + logger.info(f""Number of GPUs available: {world_size}"") + if self.gpu is not None: + if self.gpu == ""all"": + gpu = "","".join(str(i) for i in range(world_size)) + else: + gpu = self.gpu + else: + gpu = ""0"" + gpu_count = len(str(gpu).split("","")) + + if world_size > 1 and self.ddp and gpu_count > 1: + gpu = str(gpu).replace("" "", """") + os.environ['MASTER_ADDR'] = os.getenv('MASTER_ADDR', 'localhost') + os.environ['MASTER_PORT'] = os.getenv('MASTER_PORT', '19198') + os.environ['CUDA_VISIBLE_DEVICES'] = gpu + os.environ['WORLD_SIZE'] = str(world_size) + logger.info(f""Using DistributedDataParallel for multi-GPU. GPUs: {gpu}"") + else: + self.device = torch.device(""cuda:0"") + self.ddp = False + logger.info(""Using single GPU."") + else: + self.scaler = None + self.device = torch.device(""cpu"") + self.ddp = False + logger.info(""Using CPU."") + return + + def init_ddp(self, local_rank): + torch.cuda.set_device(local_rank) + os.environ['RANK'] = str(local_rank) + dist.init_process_group(backend='nccl', init_method='env://') + self.device = torch.device(""cuda"", local_rank) + + def decorate_batch(self, batch, feature_name=None): + """""" + Prepares a batch of data for processing by the model. This method is a wrapper that + delegates to a specific batch decoration method based on the data type. + + :param batch: The batch of data to be processed. + :param feature_name: (str, optional) Name of the feature used in batch decoration. Defaults to None. + + :return: The decorated batch ready for processing by the model. + """""" + return self.decorate_torch_batch(batch) + + def decorate_graph_batch(self, batch): + """""" + Prepares a graph-based batch of data for processing by the model. Specifically handles + graph-based data structures. + + :param batch: The batch of graph-based data to be processed. + + :return: A tuple of (net_input, net_target) for model processing. + """""" + net_input, net_target = {'net_input': batch.to(self.device)}, batch.y.to( + self.device + ) + if self.task in ['classification', 'multiclass', 'multilabel_classification']: + net_target = net_target.long() + else: + net_target = net_target.float() + return net_input, net_target + + def decorate_torch_batch(self, batch): + """""" + Prepares a standard PyTorch batch of data for processing by the model. Handles tensor-based data structures. + + :param batch: The batch of tensor-based data to be processed. + + :return: A tuple of (net_input, net_target) for model processing. + """""" + net_input, net_target = batch + if isinstance(net_input, dict): + net_input, net_target = { + k: v.to(self.device) for k, v in net_input.items() + }, net_target.to(self.device) + else: + net_input, net_target = { + 'net_input': net_input.to(self.device) + }, net_target.to(self.device) + if self.task == 'repr': + net_target = None + elif self.task in ['classification', 'multiclass', 'multilabel_classification']: + net_target = net_target.long() + else: + net_target = net_target.float() + return net_input, net_target + + def fit_predict( + self, + model, + train_dataset, + valid_dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler, + feature_name=None, + ): + """""" + Trains the model on the given dataset. + + :param local_rank: (int) The local rank of the current process. + :param args: Additional arguments for training. + """""" + if torch.cuda.device_count() and self.ddp: + with mp.Manager() as manager: + shared_queue = manager.Queue() + mp.spawn( + self.fit_predict_with_ddp, + args=( + shared_queue, + model, + train_dataset, + valid_dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler, + feature_name, + ), + nprocs=torch.cuda.device_count(), + ) + + try: + y_preds = shared_queue.get(timeout=1) + # print(f""Main function returned: {y_preds}"") + except: + print(""No return value received from main function."") + return y_preds + else: + return self.fit_predict_wo_ddp( + model, + train_dataset, + valid_dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler, + feature_name, + ) + + def fit_predict_wo_ddp( + self, + model, + train_dataset, + valid_dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler, + feature_name=None, + ): + """""" + Trains the model on the given training dataset and evaluates it on the validation dataset. + + :param model: The model to be trained and evaluated. + :param train_dataset: Dataset used for training the model. + :param valid_dataset: Dataset used for validating the model. + :param loss_func: The loss function used during training. + :param activation_fn: The activation function applied to the model's output. + :param dump_dir: Directory where the best model state is saved. + :param fold: The fold number in a cross-validation setting. + :param target_scaler: Scaler used for scaling the target variable. + :param feature_name: (optional) Name of the feature used in data loading. Defaults to None. + + :return: Predictions made by the model on the validation dataset. + """""" + model = model.to(self.device) + train_dataloader = NNDataLoader( + feature_name=feature_name, + dataset=train_dataset, + batch_size=self.batch_size, + shuffle=True, + collate_fn=model.batch_collate_fn, + distributed=False, + drop_last=True, + ) + optimizer, scheduler = self._initialize_optimizer_scheduler( + model, train_dataloader + ) + early_stopper = EarlyStopper( + self.patience, dump_dir, fold, self.metrics, self.metrics_str + ) + + for epoch in range(self.max_epochs): + total_trn_loss = self._train_one_epoch( + model, + train_dataloader, + optimizer, + scheduler, + loss_func, + feature_name, + epoch, + ) + + y_preds, val_loss, metric_score = self.predict( + model, + valid_dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler, + epoch, + load_model=False, + feature_name=feature_name, + ) + + self._log_epoch_results( + epoch, total_trn_loss, np.mean(val_loss), metric_score, optimizer + ) + + if early_stopper.early_stop_choice( + model, epoch, np.mean(val_loss), metric_score + ): + break + + y_preds, _, _ = self.predict( + model, + valid_dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler, + epoch, + load_model=True, + feature_name=feature_name, + ) + return y_preds + + def fit_predict_with_ddp( + self, + local_rank, + shared_queue, + model, + train_dataset, + valid_dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler, + feature_name=None, + ): + """""" + Trains the model on the given training dataset and evaluates it on the validation dataset. + + :param model: The model to be trained and evaluated. + :param train_dataset: Dataset used for training the model. + :param valid_dataset: Dataset used for validating the model. + :param loss_func: The loss function used during training. + :param activation_fn: The activation function applied to the model's output. + :param dump_dir: Directory where the best model state is saved. + :param fold: The fold number in a cross-validation setting. + :param target_scaler: Scaler used for scaling the target variable. + :param feature_name: (optional) Name of the feature used in data loading. Defaults to None. + + :return: Predictions made by the model on the validation dataset. + """""" + self.init_ddp(local_rank) + model = model.to(local_rank) + model = DistributedDataParallel( + model, device_ids=[local_rank], find_unused_parameters=True + ) + train_dataloader = NNDataLoader( + feature_name=feature_name, + dataset=train_dataset, + batch_size=self.batch_size, + shuffle=False, + collate_fn=model.module.batch_collate_fn, + distributed=True, + drop_last=True, + ) + optimizer, scheduler = self._initialize_optimizer_scheduler( + model, train_dataloader + ) + early_stopper = EarlyStopper( + self.patience, dump_dir, fold, self.metrics, self.metrics_str + ) + for epoch in range(self.max_epochs): + total_trn_loss = self._train_one_epoch( + model, + train_dataloader, + optimizer, + scheduler, + loss_func, + feature_name, + epoch, + ) + + y_preds, val_loss, metric_score = self.predict( + model, + valid_dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler, + epoch, + load_model=False, + feature_name=feature_name, + ) + + total_trn_loss = self.reduce_array(total_trn_loss) + total_val_loss = self.reduce_array(np.mean(val_loss)) + + if local_rank == 0: + # self._log_epoch_results( + # epoch, total_trn_loss, total_val_loss, metric_score, optimizer + # ) # TODO: this will generate redundant log files. + is_early_stop = early_stopper.early_stop_choice( + model, epoch, total_val_loss, metric_score + ) + if is_early_stop: + stop_flag = torch.tensor(1, device=self.device) + else: + stop_flag = torch.tensor(0, device=self.device) + else: + stop_flag = torch.tensor(0, device=self.device) + + dist.broadcast(stop_flag, src=0) + if stop_flag.item() == 1: + break + + dist.barrier() + + y_preds, _, _ = self.predict( + model, + valid_dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler, + epoch, + load_model=False, + feature_name=feature_name, + ) + y_preds = self.gather_predictions(y_preds, len_valid_dataset=len(valid_dataset)) + dist.destroy_process_group() + if local_rank == 0: + shared_queue.put(y_preds) + return y_preds + + def _initialize_optimizer_scheduler(self, model, train_dataloader): + num_training_steps = len(train_dataloader) * self.max_epochs + num_warmup_steps = int(num_training_steps * self.warmup_ratio) + optimizer = Adam(model.parameters(), lr=self.learning_rate, eps=1e-6) + scheduler = get_linear_schedule_with_warmup( + optimizer, num_warmup_steps, num_training_steps + ) + return optimizer, scheduler + + def _train_one_epoch( + self, + model, + train_dataloader, + optimizer, + scheduler, + loss_func, + feature_name, + epoch, + ): + model.train() + trn_loss = [] + batch_bar = tqdm( + total=len(train_dataloader), + dynamic_ncols=True, + leave=False, + position=0 if not self.ddp else dist.get_rank(), + desc='Train' if not self.ddp else f'Train Rank:{dist.get_rank()}', + ncols=5, + ) + if isinstance(train_dataloader.sampler, torch.utils.data.distributed.DistributedSampler): + train_dataloader.sampler.set_epoch(epoch) + for i, batch in enumerate(train_dataloader): + net_input, net_target = self.decorate_batch(batch, feature_name) + optimizer.zero_grad() + loss = self._compute_loss(model, net_input, net_target, loss_func) + trn_loss.append(float(loss.data)) + self._backward_and_step(optimizer, loss, model) + scheduler.step() + batch_bar.set_postfix( + Epoch=f""Epoch {epoch+1}/{self.max_epochs}"", + loss=f""{float(sum(trn_loss) / (i + 1)):.04f}"", + lr=f""{float(optimizer.param_groups[0]['lr']):.04f}"", + ) + batch_bar.update() + batch_bar.close() + return np.mean(trn_loss) + + def _compute_loss(self, model, net_input, net_target, loss_func): + if self.scaler and self.device.type == 'cuda': + with torch.amp.autocast(""cuda""): + outputs = model(**net_input) + loss = loss_func(outputs, net_target) + else: + with torch.set_grad_enabled(True): + outputs = model(**net_input) + loss = loss_func(outputs, net_target) + return loss + + def _backward_and_step(self, optimizer, loss, model): + if self.scaler and self.device.type == 'cuda': + self.scaler.scale(loss).backward() + self.scaler.unscale_(optimizer) + clip_grad_norm_(model.parameters(), self.max_norm) + self.scaler.step(optimizer) + self.scaler.update() + else: + loss.backward() + clip_grad_norm_(model.parameters(), self.max_norm) + optimizer.step() + + def _log_epoch_results( + self, epoch, total_trn_loss, total_val_loss, metric_score, optimizer + ): + _score = list(metric_score.values())[0] + _metric = list(metric_score.keys())[0] + message = f'Epoch [{epoch+1}/{self.max_epochs}] train_loss: {total_trn_loss:.4f}, val_loss: {total_val_loss:.4f}, val_{_metric}: {_score:.4f}, lr: {optimizer.param_groups[0][""lr""]:.6f}' + logger.info(message) + return False + + def reduce_array(self, array): + tensor = torch.tensor(array, device=self.device) + rt = tensor.clone() + dist.all_reduce(rt, op=dist.ReduceOp.SUM) + rt /= dist.get_world_size() + return rt.item() + + def gather_predictions(self, y_preds, len_valid_dataset): + y_preds_tensor = torch.tensor(y_preds, device=self.device) + gathered_y_preds = [ + torch.zeros_like(y_preds_tensor) for _ in range(dist.get_world_size()) + ] + dist.all_gather(gathered_y_preds, y_preds_tensor) + gathered_y_preds = torch.stack(gathered_y_preds, dim=1).view(-1, y_preds_tensor.size(1)) + + if len(gathered_y_preds) != len_valid_dataset: + gathered_y_preds = gathered_y_preds[ + :len_valid_dataset + ] # remove padding when using DDP + return gathered_y_preds.cpu().numpy() + + def predict( + self, + model, + dataset, + loss_func, + activation_fn, + dump_dir, + fold, + target_scaler=None, + epoch=1, + load_model=False, + feature_name=None, + ): + """""" + Executes the prediction on a given dataset using the specified model. + + :param model: The model to be used for predictions. + :param dataset: The dataset to perform predictions on. + :param loss_func: The loss function used during training. + :param activation_fn: The activation function applied to the model's output. + :param dump_dir: Directory where the model state is saved. + :param fold: The fold number in cross-validation. + :param target_scaler: (optional) Scaler to inverse transform the model's output. Defaults to None. + :param epoch: (int) The current epoch number. Defaults to 1. + :param load_model: (bool) Whether to load the model from a saved state. Defaults to False. + :param feature_name: (str, optional) Name of the feature for data processing. Defaults to None. + + :return: A tuple (y_preds, val_loss, metric_score), where y_preds are the predicted outputs, + val_loss is the validation loss, and metric_score is the calculated metric score. + """""" + model = self._prepare_model_for_prediction(model, dump_dir, fold, load_model) + if isinstance(model, DistributedDataParallel): + batch_collate_fn = model.module.batch_collate_fn + else: + batch_collate_fn = model.batch_collate_fn + dataloader = NNDataLoader( + feature_name=feature_name, + dataset=dataset, + batch_size=self.batch_size, + shuffle=False, + collate_fn=batch_collate_fn, + distributed=self.ddp, + valid_mode=True, + ) + y_preds, val_loss, y_truths = self._perform_prediction( + model, dataloader, loss_func, activation_fn, load_model, epoch, feature_name + ) + + metric_score = self._calculate_metrics( + y_preds, y_truths, target_scaler, model, load_model + ) + return y_preds, val_loss, metric_score + + def _prepare_model_for_prediction(self, model, dump_dir, fold, load_model): + model = model.to(self.device) + if load_model: + load_model_path = os.path.join(dump_dir, f'model_{fold}.pth') + model.load_pretrained_weights(load_model_path, strict=True) + logger.info(""load model success!"") + return model + + def _perform_prediction( + self, + model, + dataloader, + loss_func, + activation_fn, + load_model, + epoch, + feature_name, + ): + model = model.eval() + batch_bar = tqdm( + total=len(dataloader), + dynamic_ncols=True, + position=0, + leave=False, + desc='val', + ncols=5, + ) + val_loss = [] + y_preds = [] + y_truths = [] + for i, batch in enumerate(dataloader): + net_input, net_target = self.decorate_batch(batch, feature_name) + with torch.no_grad(): + outputs = model(**net_input) + if not load_model: + loss = loss_func(outputs, net_target) + val_loss.append(float(loss.data)) + y_preds.append(activation_fn(outputs).cpu().numpy()) + y_truths.append(net_target.detach().cpu().numpy()) + if not load_model: + batch_bar.set_postfix( + Epoch=""Epoch {}/{}"".format(epoch + 1, self.max_epochs), + loss=""{:.04f}"".format(float(np.sum(val_loss) / (i + 1))), + ) + batch_bar.update() + batch_bar.close() + y_preds = np.concatenate(y_preds) + y_truths = np.concatenate(y_truths) + return y_preds, val_loss, y_truths + + def _calculate_metrics(self, y_preds, y_truths, target_scaler, model, load_model): + try: + label_cnt = model.output_dim + except: + label_cnt = None + if target_scaler is not None: + inverse_y_preds = target_scaler.inverse_transform(y_preds) + inverse_y_truths = target_scaler.inverse_transform(y_truths) + metric_score = ( + self.metrics.cal_metric( + inverse_y_truths, inverse_y_preds, label_cnt=label_cnt + ) + if not load_model + else None + ) + else: + metric_score = ( + self.metrics.cal_metric(y_truths, y_preds, label_cnt=label_cnt) + if not load_model + else None + ) + return metric_score + + def inference( + self, + model, + dataset, + model_name, + return_repr=False, + return_atomic_reprs=False, + feature_name=None, + return_tensor=False, + ): + """""" + Runs inference on the given dataset using the provided model. This method can return + various representations based on the model's output. + + :param model: The neural network model to be used for inference. + :param dataset: The dataset on which inference is to be performed. + :param model_name: The name of neural network model. + :param return_repr: (bool, optional) If True, returns class-level representations. Defaults to False. + :param return_atomic_reprs: (bool, optional) If True, returns atomic-level representations. Defaults to False. + :param feature_name: (str, optional) Name of the feature used for data loading. Defaults to None. + :param return_tensor: (str, optional) If True, returns tensor representations, only works when return_atomic_reprs=False. Defaults to False. + + :return: A dictionary containing different types of representations based on the model's output and the + specified parameters. This can include class-level representations, atomic coordinates, + atomic representations, and atomic symbols. + """""" + if torch.cuda.device_count() and self.ddp: + with mp.Manager() as manager: + shared_queue = manager.Queue() + mp.spawn( + self.inference_with_ddp, + args=( + shared_queue, + model, + dataset, + model_name, + return_repr, + return_atomic_reprs, + feature_name, + return_tensor, + ), + nprocs=torch.cuda.device_count(), + ) + try: + repr_ = shared_queue.get(timeout=1) + except: + print(""No return value received from main function."") + return repr_ + else: + return self.inference_without_ddp( + model, dataset, model_name, return_repr, return_atomic_reprs, feature_name, return_tensor + ) + + def inference_with_ddp( + self, + local_rank, + shared_queue, + model, + dataset, + model_name, + return_repr=False, + return_atomic_reprs=False, + feature_name=None, + return_tensor=False, + ): + """""" + Runs inference on the given dataset using the provided model with DistributedDataParallel (DDP). + + :param local_rank: The local rank of the current process. + :param shared_queue: A shared queue to store the inference results. + :param model: The neural network model to be used for inference. + :param dataset: The dataset on which inference is to be performed. + :param model_name: The name of neural network model. + :param return_repr: (bool, optional) If True, returns class-level representations. Defaults to False. + :param return_atomic_reprs: (bool, optional) If True, returns atomic-level representations. Defaults to False. + :param feature_name: (str, optional) Name of the feature used for data loading. Defaults to None. + :param return_tensor: (str, optional) If True, returns tensor representations, only works when return_atomic_reprs=False. Defaults to False. + + :return: A dictionary containing different types of representations based on the model's output and the + specified parameters. This can include class-level representations, atomic coordinates, + atomic representations, and atomic symbols. + """""" + self.init_ddp(local_rank) + model = model.to(local_rank) + model = DistributedDataParallel( + model, device_ids=[local_rank], find_unused_parameters=True + ) + dataloader = NNDataLoader( + feature_name=feature_name, + dataset=dataset, + batch_size=self.batch_size, + shuffle=False, + collate_fn=model.module.batch_collate_fn, + distributed=True, + ) + model = model.eval() + if return_atomic_reprs: + repr_dict = { + ""cls_repr"": [], + ""atomic_coords"": [], + ""atomic_reprs"": [], + ""atomic_symbol"": [], + } + for batch in tqdm(dataloader): + net_input, _ = self.decorate_batch(batch, feature_name) + with torch.no_grad(): + outputs = model( + **net_input, + return_repr=return_repr, + return_atomic_reprs=return_atomic_reprs, + ) + + assert isinstance(outputs, dict) + repr_dict[""cls_repr""].extend( + item.cpu().numpy() for item in outputs[""cls_repr""] + ) + if model_name == 'unimolv1': + repr_dict[""atomic_symbol""].extend( + outputs[""atomic_symbol""] + ) + elif model_name == 'unimolv2': + repr_dict[""atomic_symbol""].extend( + item.cpu().numpy() for item in outputs[""atomic_symbol""] + ) + repr_dict['atomic_coords'].extend( + item.cpu().numpy() for item in outputs['atomic_coords'] + ) + repr_dict['atomic_reprs'].extend( + item.cpu().numpy() for item in outputs['atomic_reprs'] + ) + + world_size = dist.get_world_size() + gathered_list = [{} for _ in range(world_size)] + dist.gather_object(repr_dict, gathered_list if local_rank == 0 else None, dst=0) + dist.destroy_process_group() + + if local_rank == 0: + merged_repr_dict = { + ""cls_repr"": [], + 'atomic_coords': [], + ""atomic_reprs"": [], + ""atomic_symbol"": [], + } + + max_local = max(len(rd[""cls_repr""]) for rd in gathered_list) + total = len(dataset) + + for i in range(max_local): + for r in range(world_size): + global_idx = i * world_size + r + if global_idx >= total: + continue + rd = gathered_list[r] + if i < len(rd[""cls_repr""]): + merged_repr_dict[""cls_repr""].append(rd[""cls_repr""][i]) + merged_repr_dict[""atomic_symbol""].append( + rd[""atomic_symbol""][i] + ) + merged_repr_dict[""atomic_coords""].append( + rd[""atomic_coords""][i] + ) + merged_repr_dict[""atomic_reprs""].append( + rd[""atomic_reprs""][i] + ) + shared_queue.put(merged_repr_dict) + return + else: + if return_tensor: + repr_tensor = [] + for batch in tqdm(dataloader): + net_input, _ = self.decorate_batch(batch, feature_name) + with torch.no_grad(): + outputs = model( + **net_input, + return_repr=return_repr, + return_atomic_reprs=return_atomic_reprs, + ) + assert isinstance(outputs, torch.Tensor) + repr_tensor.append(outputs.cpu().numpy()) + repr_tensor = np.concatenate(repr_tensor, axis=0) + + gathered_list = [None for _ in range(dist.get_world_size())] + dist.gather_object( + repr_tensor, gathered_list if local_rank == 0 else None, dst=0 + ) + dist.destroy_process_group() + + if local_rank == 0: + merged_numpy = np.stack(gathered_list, axis=1).reshape(-1, repr_tensor.shape[-1]) + merged_numpy = merged_numpy[: len(dataset)] + merged_tensor = torch.from_numpy(merged_numpy) + shared_queue.put(merged_tensor) + return + else: + repr_list = [] + for batch in tqdm(dataloader): + net_input, _ = self.decorate_batch(batch, feature_name) + with torch.no_grad(): + outputs = model( + **net_input, + return_repr=return_repr, + return_atomic_reprs=return_atomic_reprs, + ) + assert isinstance(outputs, torch.Tensor) + repr_list.extend(item.cpu().numpy() for item in outputs) + + world_size = dist.get_world_size() + gathered_list = [None for _ in range(world_size)] + dist.gather_object( + repr_list, gathered_list if local_rank == 0 else None, dst=0 + ) + dist.destroy_process_group() + if local_rank == 0: + merged_list = [] + + max_local = max(len(rl) for rl in gathered_list) + total = len(dataset) + for i in range(max_local): + for r in range(world_size): + global_idx = i * world_size + r + if global_idx >= total: + continue + rl = gathered_list[r] + if i < len(rl): + merged_list.append(rl[i]) + merged_list = merged_list[: len(dataset)] + shared_queue.put(merged_list) + return + + def inference_without_ddp( + self, + model, + dataset, + model_name, + return_repr=False, + return_atomic_reprs=False, + feature_name=None, + return_tensor=False, + ): + """""" + Runs inference on the given dataset using the provided model without DistributedDataParallel (DDP). + + :param model: The neural network model to be used for inference. + :param dataset: The dataset on which inference is to be performed. + :param model_name: The name of neural network model. + :param return_repr: (bool, optional) If True, returns class-level representations. Defaults to False. + :param return_atomic_reprs: (bool, optional) If True, returns atomic-level representations. Defaults to False. + :param feature_name: (str, optional) Name of the feature used for data loading. Defaults to None. + :param return_tensor: (str, optional) If True, returns tensor representations, only works when return_atomic_reprs=False. Defaults to False. + + :return: A dictionary containing different types of representations based on the model's output and the + specified parameters. This can include class-level representations, atomic coordinates, + atomic representations, and atomic symbols. + """""" + model = model.to(self.device) + dataloader = NNDataLoader( + feature_name=feature_name, + dataset=dataset, + batch_size=self.batch_size, + shuffle=False, + collate_fn=model.batch_collate_fn, + distributed=False, + ) + model = model.eval() + if return_atomic_reprs: + repr_dict = { + ""cls_repr"": [], + ""atomic_coords"": [], + ""atomic_reprs"": [], + ""atomic_symbol"": [], + } + for batch in tqdm(dataloader): + net_input, _ = self.decorate_batch(batch, feature_name) + with torch.no_grad(): + outputs = model( + **net_input, + return_repr=return_repr, + return_atomic_reprs=return_atomic_reprs, + ) + assert isinstance(outputs, dict) + repr_dict[""cls_repr""].extend( + item.cpu().numpy() for item in outputs[""cls_repr""] + ) + if model_name == 'unimolv1': + repr_dict[""atomic_symbol""].extend(outputs[""atomic_symbol""]) + elif model_name == 'unimolv2': + repr_dict[""atomic_symbol""].extend( + item.cpu().numpy() for item in outputs[""atomic_symbol""] + ) + repr_dict[""atomic_coords""].extend( + item.cpu().numpy() for item in outputs['atomic_coords'] + ) + repr_dict[""atomic_reprs""].extend( + item.cpu().numpy() for item in outputs['atomic_reprs'] + ) + return repr_dict + else: + if return_tensor: + repr_tensor = [] + for batch in tqdm(dataloader): + net_input, _ = self.decorate_batch(batch, feature_name) + with torch.no_grad(): + outputs = model( + **net_input, + return_repr=return_repr, + return_atomic_reprs=return_atomic_reprs, + ) + assert isinstance(outputs, torch.Tensor) + repr_tensor.append(outputs.cpu().numpy()) + repr_tensor = np.concatenate(repr_tensor, axis=0) + repr_tensor = torch.from_numpy(repr_tensor) + return repr_tensor + else: + repr_list = [] + for batch in tqdm(dataloader): + net_input, _ = self.decorate_batch(batch, feature_name) + with torch.no_grad(): + outputs = model( + **net_input, + return_repr=return_repr, + return_atomic_reprs=return_atomic_reprs, + ) + assert isinstance(outputs, torch.Tensor) + repr_list.extend( + item.cpu().numpy() for item in outputs + ) + return repr_list + + def set_seed(self, seed): + """""" + Sets a random seed for torch and numpy to ensure reproducibility. + :param seed: (int) The seed number to be set. + """""" + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + np.random.seed(seed) + + +class EarlyStopper: + def __init__(self, patience, dump_dir, fold, metrics, metrics_str): + """""" + Initializes the EarlyStopper class. + + :param patience: The number of epochs to wait for an improvement before stopping. + :param dump_dir: Directory to save the model state. + :param fold: The current fold number in a cross-validation setting. + """""" + self.patience = patience + self.dump_dir = dump_dir + self.fold = fold + self.metrics = metrics + self.metrics_str = metrics_str + self.wait = 0 + self.min_loss = float(""inf"") + self.max_loss = float(""-inf"") + self.is_early_stop = False + + def early_stop_choice(self, model, epoch, loss, metric_score=None): + """""" + Determines if early stopping criteria are met, based on either loss improvement or custom metric score. + + :param model: The model being trained. + :param epoch: The current epoch number. + :param loss: The current loss value. + :param metric_score: The current metric score. + + :return: A boolean indicating whether early stopping should occur. + """""" + if not isinstance(self.metrics_str, str) or self.metrics_str in [ + 'loss', + 'none', + '', + ]: + return self._judge_early_stop_loss(loss, model, epoch) + else: + is_early_stop, min_score, wait, max_score = self.metrics._early_stop_choice( + self.wait, + self.min_loss, + metric_score, + self.max_loss, + model, + self.dump_dir, + self.fold, + self.patience, + epoch, + ) + self.min_loss = min_score + self.max_loss = max_score + self.wait = wait + self.is_early_stop = is_early_stop + return self.is_early_stop + + def _judge_early_stop_loss(self, loss, model, epoch): + """""" + Determines whether early stopping should be triggered based on the loss comparison. + + :param loss: The current loss value of the model. + :param model: The neural network model being trained. + :param epoch: The current epoch number. + + :return: A boolean indicating whether early stopping should occur. + """""" + if loss <= self.min_loss: + self.min_loss = loss + self.wait = 0 + if isinstance(model, DistributedDataParallel): + model = model.module + info = {'model_state_dict': model.state_dict()} + os.makedirs(self.dump_dir, exist_ok=True) + torch.save(info, os.path.join(self.dump_dir, f'model_{self.fold}.pth')) + else: + self.wait += 1 + if self.wait >= self.patience: + logger.warning(f'Early stopping at epoch: {epoch+1}') + self.is_early_stop = True + return self.is_early_stop + + +def NNDataLoader( + feature_name=None, + dataset=None, + batch_size=None, + shuffle=False, + collate_fn=None, + drop_last=False, + distributed=False, + valid_mode=False, +): + """""" + Creates a DataLoader for neural network training or inference. This + function is a wrapper around the standard PyTorch DataLoader, allowing + for custom feature handling and additional configuration. + + :param feature_name: (str, optional) Name of the feature used for data loading. + This can be used to specify a particular type of data processing. Defaults to None. + :param dataset: (Dataset, optional) The dataset from which to load the data. Defaults to None. + :param batch_size: (int, optional) Number of samples per batch to load. Defaults to None. + :param shuffle: (bool, optional) Whether to shuffle the data at every epoch. Defaults to False. + :param collate_fn: (callable, optional) Merges a list of samples to form a mini-batch. Defaults to None. + :param drop_last: (bool, optional) Set to True to drop the last incomplete batch. Defaults to False. + :param distributed: (bool, optional) Set to True to enable distributed data loading. Defaults to False. + + :return: DataLoader configured according to the provided parameters. + """""" + + if distributed: + sampler = DistributedSampler(dataset, shuffle=shuffle) + g = get_ddp_generator() + else: + sampler = None + g = None + + if valid_mode: + g = None + + dataloader = TorchDataLoader( + dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + collate_fn=collate_fn, + drop_last=drop_last, + # num_workers=4, + pin_memory=True, + sampler=sampler, + generator=g, + ) + return dataloader + + +def get_ddp_generator(seed=3407): + local_rank = dist.get_rank() + g = torch.Generator() + g.manual_seed(seed + local_rank) + return g + + +# source from https://github.com/huggingface/transformers/blob/main/src/transformers/optimization.py#L108C1-L132C54 +def _get_linear_schedule_with_warmup_lr_lambda( + current_step: int, *, num_warmup_steps: int, num_training_steps: int +): + if current_step < num_warmup_steps: + return float(current_step) / float(max(1, num_warmup_steps)) + return max( + 0.0, + float(num_training_steps - current_step) + / float(max(1, num_training_steps - num_warmup_steps)), + ) + + +def get_linear_schedule_with_warmup( + optimizer, num_warmup_steps, num_training_steps, last_epoch=-1 +): + """""" + Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after + a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. + + Args: + optimizer ([`~torch.optim.Optimizer`]): + The optimizer for which to schedule the learning rate. + num_warmup_steps (`int`): + The number of steps for the warmup phase. + num_training_steps (`int`): + The total number of training steps. + last_epoch (`int`, *optional*, defaults to -1): + The index of the last epoch when resuming training. + + Return: + `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. + """""" + + lr_lambda = partial( + _get_linear_schedule_with_warmup_lr_lambda, + num_warmup_steps=num_warmup_steps, + num_training_steps=num_training_steps, + ) + return LambdaLR(optimizer, lr_lambda, last_epoch) +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/tasks/__init__.py",".py","29","2","from .trainer import Trainer +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/models/transformers.py",".py","15882","437","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + + +def softmax_dropout( + input, dropout_prob, is_training=True, mask=None, bias=None, inplace=True +): + """"""softmax dropout, and mask, bias are optional. + + Args: + input (torch.Tensor): input tensor + dropout_prob (float): dropout probability + is_training (bool, optional): is in training or not. Defaults to True. + mask (torch.Tensor, optional): the mask tensor, use as input + mask . Defaults to None. + bias (torch.Tensor, optional): the bias tensor, use as input + bias . Defaults to None. + + Returns: + torch.Tensor: the result after softmax + """""" + input = input.contiguous() + if not inplace: + # copy a input for non-inplace case + input = input.clone() + if mask is not None: + input += mask + if bias is not None: + input += bias + return F.dropout(F.softmax(input, dim=-1), p=dropout_prob, training=is_training) + + +def get_activation_fn(activation): + """"""Returns the activation function corresponding to `activation`"""""" + + if activation == ""relu"": + return F.relu + elif activation == ""gelu"": + return F.gelu + elif activation == ""tanh"": + return torch.tanh + elif activation == ""linear"": + return lambda x: x + else: + raise RuntimeError(""--activation-fn {} not supported"".format(activation)) + + +def init_bert_params(module): + """"""Initialize weights the same way as the original Uni-Mol BERT modules."""""" + if not getattr(module, ""can_global_init"", True): + return + if isinstance(module, nn.Linear): + nn.init.normal_(module.weight, mean=0.0, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=0.02) + if module.padding_idx is not None: + nn.init.zeros_(module.weight[module.padding_idx]) + + +class SelfMultiheadAttention(nn.Module): + def __init__( + self, + embed_dim, + num_heads, + dropout=0.1, + bias=True, + scaling_factor=1, + ): + super().__init__() + self.embed_dim = embed_dim + + self.num_heads = num_heads + self.dropout = dropout + + self.head_dim = embed_dim // num_heads + assert ( + self.head_dim * num_heads == self.embed_dim + ), ""embed_dim must be divisible by num_heads"" + self.scaling = (self.head_dim * scaling_factor) ** -0.5 + + self.in_proj = nn.Linear(embed_dim, embed_dim * 3, bias=bias) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + def forward( + self, + query, + key_padding_mask: Optional[Tensor] = None, + attn_bias: Optional[Tensor] = None, + return_attn: bool = False, + ) -> Tensor: + + bsz, tgt_len, embed_dim = query.size() + assert embed_dim == self.embed_dim + + q, k, v = self.in_proj(query).chunk(3, dim=-1) + + q = ( + q.view(bsz, tgt_len, self.num_heads, self.head_dim) + .transpose(1, 2) + .contiguous() + .view(bsz * self.num_heads, -1, self.head_dim) + * self.scaling + ) + if k is not None: + k = ( + k.view(bsz, -1, self.num_heads, self.head_dim) + .transpose(1, 2) + .contiguous() + .view(bsz * self.num_heads, -1, self.head_dim) + ) + if v is not None: + v = ( + v.view(bsz, -1, self.num_heads, self.head_dim) + .transpose(1, 2) + .contiguous() + .view(bsz * self.num_heads, -1, self.head_dim) + ) + + assert k is not None + src_len = k.size(1) + + # This is part of a workaround to get around fork/join parallelism + # not supporting Optional types. + if key_padding_mask is not None and key_padding_mask.dim() == 0: + key_padding_mask = None + + if key_padding_mask is not None: + assert key_padding_mask.size(0) == bsz + assert key_padding_mask.size(1) == src_len + + attn_weights = torch.bmm(q, k.transpose(1, 2)) + + assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len] + + if key_padding_mask is not None: + # don't attend to padding symbols + attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights.masked_fill_( + key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), float(""-inf"") + ) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + if not return_attn: + attn = softmax_dropout( + attn_weights, + self.dropout, + self.training, + bias=attn_bias, + ) + else: + attn_weights += attn_bias + attn = softmax_dropout( + attn_weights, + self.dropout, + self.training, + inplace=False, + ) + + o = torch.bmm(attn, v) + assert list(o.size()) == [bsz * self.num_heads, tgt_len, self.head_dim] + + o = ( + o.view(bsz, self.num_heads, tgt_len, self.head_dim) + .transpose(1, 2) + .contiguous() + .view(bsz, tgt_len, embed_dim) + ) + o = self.out_proj(o) + if not return_attn: + return o + else: + return o, attn_weights, attn + + +class TransformerEncoderLayer(nn.Module): + """""" + Implements a Transformer Encoder Layer used in BERT/XLM style pre-trained + models. + """""" + + def __init__( + self, + embed_dim: int = 768, + ffn_embed_dim: int = 3072, + attention_heads: int = 8, + dropout: float = 0.1, + attention_dropout: float = 0.1, + activation_dropout: float = 0.0, + activation_fn: str = ""gelu"", + post_ln=False, + ) -> None: + super().__init__() + + # Initialize parameters + self.embed_dim = embed_dim + self.attention_heads = attention_heads + self.attention_dropout = attention_dropout + + self.dropout = dropout + self.activation_dropout = activation_dropout + self.activation_fn = get_activation_fn(activation_fn) + + self.self_attn = SelfMultiheadAttention( + self.embed_dim, + attention_heads, + dropout=attention_dropout, + ) + # layer norm associated with the self attention layer + self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) + self.fc1 = nn.Linear(self.embed_dim, ffn_embed_dim) + self.fc2 = nn.Linear(ffn_embed_dim, self.embed_dim) + self.final_layer_norm = nn.LayerNorm(self.embed_dim) + self.post_ln = post_ln + + def forward( + self, + x: torch.Tensor, + attn_bias: Optional[torch.Tensor] = None, + padding_mask: Optional[torch.Tensor] = None, + return_attn: bool = False, + ) -> torch.Tensor: + """""" + LayerNorm is applied either before or after the self-attention/ffn + modules similar to the original Transformer implementation. + """""" + residual = x + if not self.post_ln: + x = self.self_attn_layer_norm(x) + # new added + x = self.self_attn( + query=x, + key_padding_mask=padding_mask, + attn_bias=attn_bias, + return_attn=return_attn, + ) + if return_attn: + x, attn_weights, attn_probs = x + x = F.dropout(x, p=self.dropout, training=self.training) + x = residual + x + if self.post_ln: + x = self.self_attn_layer_norm(x) + + residual = x + if not self.post_ln: + x = self.final_layer_norm(x) + x = self.fc1(x) + x = self.activation_fn(x) + x = F.dropout(x, p=self.activation_dropout, training=self.training) + x = self.fc2(x) + x = F.dropout(x, p=self.dropout, training=self.training) + x = residual + x + if self.post_ln: + x = self.final_layer_norm(x) + if not return_attn: + return x + else: + return x, attn_weights, attn_probs + + +class TransformerEncoderWithPair(nn.Module): + """""" + A custom Transformer Encoder module that extends PyTorch's nn.Module. This encoder is designed for tasks that require understanding pair relationships in sequences. It includes standard transformer encoder layers along with additional normalization and dropout features. + + Attributes: + - emb_dropout: Dropout rate applied to the embedding layer. + - max_seq_len: Maximum length of the input sequences. + - embed_dim: Dimensionality of the embeddings. + - attention_heads: Number of attention heads in the transformer layers. + - emb_layer_norm: Layer normalization applied to the embedding layer. + - final_layer_norm: Optional final layer normalization. + - final_head_layer_norm: Optional layer normalization for the attention heads. + - layers: A list of transformer encoder layers. + + Methods: + forward: Performs the forward pass of the module. + """""" + + def __init__( + self, + encoder_layers: int = 6, + embed_dim: int = 768, + ffn_embed_dim: int = 3072, + attention_heads: int = 8, + emb_dropout: float = 0.1, + dropout: float = 0.1, + attention_dropout: float = 0.1, + activation_dropout: float = 0.0, + max_seq_len: int = 256, + activation_fn: str = ""gelu"", + post_ln: bool = False, + no_final_head_layer_norm: bool = False, + ) -> None: + """""" + Initializes and configures the layers and other components of the transformer encoder. + + :param encoder_layers: (int) Number of encoder layers in the transformer. + :param embed_dim: (int) Dimensionality of the input embeddings. + :param ffn_embed_dim: (int) Dimensionality of the feedforward network model. + :param attention_heads: (int) Number of attention heads in each encoder layer. + :param emb_dropout: (float) Dropout rate for the embedding layer. + :param dropout: (float) Dropout rate for the encoder layers. + :param attention_dropout: (float) Dropout rate for the attention mechanisms. + :param activation_dropout: (float) Dropout rate for activations. + :param max_seq_len: (int) Maximum sequence length the model can handle. + :param activation_fn: (str) The activation function to use (e.g., ""gelu""). + :param post_ln: (bool) If True, applies layer normalization after the feedforward network. + :param no_final_head_layer_norm: (bool) If True, does not apply layer normalization to the final attention head. + + """""" + super().__init__() + self.emb_dropout = emb_dropout + self.max_seq_len = max_seq_len + self.embed_dim = embed_dim + self.attention_heads = attention_heads + self.emb_layer_norm = nn.LayerNorm(self.embed_dim) + if not post_ln: + self.final_layer_norm = nn.LayerNorm(self.embed_dim) + else: + self.final_layer_norm = None + + if not no_final_head_layer_norm: + self.final_head_layer_norm = nn.LayerNorm(attention_heads) + else: + self.final_head_layer_norm = None + + self.layers = nn.ModuleList( + [ + TransformerEncoderLayer( + embed_dim=self.embed_dim, + ffn_embed_dim=ffn_embed_dim, + attention_heads=attention_heads, + dropout=dropout, + attention_dropout=attention_dropout, + activation_dropout=activation_dropout, + activation_fn=activation_fn, + post_ln=post_ln, + ) + for _ in range(encoder_layers) + ] + ) + + def forward( + self, + emb: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + padding_mask: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """""" + Conducts the forward pass of the transformer encoder. + + :param emb: (torch.Tensor) The input tensor of embeddings. + :param attn_mask: (Optional[torch.Tensor]) Attention mask to specify positions to attend to. + :param padding_mask: (Optional[torch.Tensor]) Mask to indicate padded elements in the input. + + :return: (torch.Tensor) The output tensor after passing through the transformer encoder layers. + It also returns tensors related to pair representation and normalization losses. + """""" + bsz = emb.size(0) + seq_len = emb.size(1) + x = self.emb_layer_norm(emb) + x = F.dropout(x, p=self.emb_dropout, training=self.training) + # account for padding while computing the representation + if padding_mask is not None: + x = x * (1 - padding_mask.unsqueeze(-1).type_as(x)) + input_attn_mask = attn_mask + input_padding_mask = padding_mask + + def fill_attn_mask(attn_mask, padding_mask, fill_val=float(""-inf"")): + if attn_mask is not None and padding_mask is not None: + # merge key_padding_mask and attn_mask + attn_mask = attn_mask.view(x.size(0), -1, seq_len, seq_len) + attn_mask.masked_fill_( + padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), + fill_val, + ) + attn_mask = attn_mask.view(-1, seq_len, seq_len) + padding_mask = None + return attn_mask, padding_mask + + assert attn_mask is not None + attn_mask, padding_mask = fill_attn_mask(attn_mask, padding_mask) + for i in range(len(self.layers)): + x, attn_mask, _ = self.layers[i]( + x, padding_mask=padding_mask, attn_bias=attn_mask, return_attn=True + ) + + def norm_loss(x, eps=1e-10, tolerance=1.0): + x = x.float() + max_norm = x.shape[-1] ** 0.5 + norm = torch.sqrt(torch.sum(x**2, dim=-1) + eps) + error = torch.nn.functional.relu((norm - max_norm).abs() - tolerance) + return error + + def masked_mean(mask, value, dim=-1, eps=1e-10): + return ( + torch.sum(mask * value, dim=dim) / (eps + torch.sum(mask, dim=dim)) + ).mean() + + x_norm = norm_loss(x) + if input_padding_mask is not None: + token_mask = 1.0 - input_padding_mask.float() + else: + token_mask = torch.ones_like(x_norm, device=x_norm.device) + x_norm = masked_mean(token_mask, x_norm) + + if self.final_layer_norm is not None: + x = self.final_layer_norm(x) + + delta_pair_repr = attn_mask - input_attn_mask + delta_pair_repr, _ = fill_attn_mask(delta_pair_repr, input_padding_mask, 0) + attn_mask = ( + attn_mask.view(bsz, -1, seq_len, seq_len).permute(0, 2, 3, 1).contiguous() + ) + delta_pair_repr = ( + delta_pair_repr.view(bsz, -1, seq_len, seq_len) + .permute(0, 2, 3, 1) + .contiguous() + ) + + pair_mask = token_mask[..., None] * token_mask[..., None, :] + delta_pair_repr_norm = norm_loss(delta_pair_repr) + delta_pair_repr_norm = masked_mean( + pair_mask, delta_pair_repr_norm, dim=(-1, -2) + ) + + if self.final_head_layer_norm is not None: + delta_pair_repr = self.final_head_layer_norm(delta_pair_repr) + + return x, attn_mask, delta_pair_repr, x_norm, delta_pair_repr_norm +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/models/loss.py",".py","8247","249","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn.functional as F +from torch import nn + + +class GHM_Loss(nn.Module): + """"""A :class:`GHM_Loss` class."""""" + + def __init__(self, bins=10, alpha=0.5): + """""" + Initializes the GHM_Loss module with the specified number of bins and alpha value. + + :param bins: (int) The number of bins to divide the gradient. Defaults to 10. + :param alpha: (float) The smoothing parameter for updating the last bin count. Defaults to 0.5. + """""" + super(GHM_Loss, self).__init__() + self._bins = bins + self._alpha = alpha + self._last_bin_count = None + + def _g2bin(self, g): + """""" + Maps gradient values to corresponding bin indices. + + :param g: (torch.Tensor) Gradient tensor. + :return: (torch.Tensor) Bin indices for each gradient value. + """""" + return torch.floor(g * (self._bins - 0.0001)).long() + + def _custom_loss(self, x, target, weight): + """""" + Custom loss function to be implemented in subclasses. + + :param x: (torch.Tensor) Predicted values. + :param target: (torch.Tensor) Ground truth labels. + :param weight: (torch.Tensor) Weights for the loss. + :raise NotImplementedError: Indicates that the method should be implemented in subclasses. + """""" + raise NotImplementedError + + def _custom_loss_grad(self, x, target): + """""" + Custom gradient computation function to be implemented in subclasses. + + :param x: (torch.Tensor) Predicted values. + :param target: (torch.Tensor) Ground truth labels. + :raise NotImplementedError: Indicates that the method should be implemented in subclasses. + """""" + raise NotImplementedError + + def forward(self, x, target): + """""" + Forward pass for computing the GHM loss. + + :param x: (torch.Tensor) Predicted values. + :param target: (torch.Tensor) Ground truth labels. + :return: (torch.Tensor) Computed GHM loss. + """""" + g = torch.abs(self._custom_loss_grad(x, target)).detach() + + bin_idx = self._g2bin(g) + + bin_count = torch.zeros((self._bins)) + for i in range(self._bins): + bin_count[i] = (bin_idx == i).sum().item() + + N = x.size(0) * x.size(1) + + if self._last_bin_count is None: + self._last_bin_count = bin_count + else: + bin_count = ( + self._alpha * self._last_bin_count + (1 - self._alpha) * bin_count + ) + self._last_bin_count = bin_count + + nonempty_bins = (bin_count > 0).sum().item() + + gd = bin_count * nonempty_bins + gd = torch.clamp(gd, min=0.0001) + beta = N / gd + + beta = beta.type_as(x) + + return self._custom_loss(x, target, beta[bin_idx]) + + +class GHMC_Loss(GHM_Loss): + ''' + Inherits from GHM_Loss. GHM_Loss for classification. + ''' + + def __init__(self, bins, alpha): + """""" + Initializes the GHMC_Loss with specified number of bins and alpha value. + + :param bins: (int) Number of bins for gradient division. + :param alpha: (float) Smoothing parameter for bin count updating. + """""" + super(GHMC_Loss, self).__init__(bins, alpha) + + def _custom_loss(self, x, target, weight): + """""" + Custom loss function for GHM classification loss. + + :param x: (torch.Tensor) Predicted values. + :param target: (torch.Tensor) Ground truth labels. + :param weight: (torch.Tensor) Weights for the loss. + + :return: Binary cross-entropy loss with logits. + """""" + return F.binary_cross_entropy_with_logits(x, target, weight=weight) + + def _custom_loss_grad(self, x, target): + """""" + Custom gradient function for GHM classification loss. + + :param x: (torch.Tensor) Predicted values. + :param target: (torch.Tensor) Ground truth labels. + + :return: Gradient of the loss. + """""" + return torch.sigmoid(x).detach() - target + + +class GHMR_Loss(GHM_Loss): + ''' + Inherits from GHM_Loss. GHM_Loss for regression + ''' + + def __init__(self, bins, alpha, mu): + """""" + Initializes the GHMR_Loss with specified number of bins, alpha value, and mu parameter. + + :param bins: (int) Number of bins for gradient division. + :param alpha: (float) Smoothing parameter for bin count updating. + :param mu: (float) Parameter used in the GHMR loss formula. + """""" + super(GHMR_Loss, self).__init__(bins, alpha) + self._mu = mu + + def _custom_loss(self, x, target, weight): + """""" + Custom loss function for GHM regression loss. + + :param x: (torch.Tensor) Predicted values. + :param target: (torch.Tensor) Ground truth values. + :param weight: (torch.Tensor) Weights for the loss. + + :return: GHMR loss. + """""" + d = x - target + mu = self._mu + loss = torch.sqrt(d * d + mu * mu) - mu + N = x.size(0) * x.size(1) + return (loss * weight).sum() / N + + def _custom_loss_grad(self, x, target): + """""" + Custom gradient function for GHM regression loss. + + :param x: (torch.Tensor) Predicted values. + :param target: (torch.Tensor) Ground truth values. + + :return: Gradient of the loss. + """""" + d = x - target + mu = self._mu + return d / torch.sqrt(d * d + mu * mu) + + +def MAEwithNan(y_pred, y_true): + """""" + Calculates the Mean Absolute Error (MAE) loss, ignoring NaN values in the target. + + :param y_pred: (torch.Tensor) Predicted values. + :param y_true: (torch.Tensor) Ground truth values, may contain NaNs. + + :return: (torch.Tensor) MAE loss computed only on non-NaN elements. + """""" + mask = ~torch.isnan(y_true) + y_pred = y_pred[mask] + y_true = y_true[mask] + mae_loss = nn.L1Loss() + loss = mae_loss(y_pred, y_true) + return loss + + +def FocalLoss(y_pred, y_true, alpha=0.25, gamma=2): + """""" + Calculates the Focal Loss, used to address class imbalance by focusing on hard examples. + + :param y_pred: (torch.Tensor) Predicted probabilities. + :param y_true: (torch.Tensor) Ground truth labels. + :param alpha: (float) Weighting factor for balancing positive and negative examples. Defaults to 0.25. + :param gamma: (float) Focusing parameter to scale the loss. Defaults to 2. + + :return: (torch.Tensor) Computed focal loss. + """""" + if y_pred.shape != y_true.shape: + y_true = y_true.flatten() + y_true = y_true.long() + y_pred = y_pred.float() + y_true = y_true.float() + y_true = y_true.unsqueeze(1) + y_pred = y_pred.unsqueeze(1) + y_true = torch.cat((1 - y_true, y_true), dim=1) + y_pred = torch.cat((1 - y_pred, y_pred), dim=1) + y_pred = y_pred.clamp(1e-5, 1.0) + loss = -alpha * y_true * torch.pow((1 - y_pred), gamma) * torch.log(y_pred) + return torch.mean(torch.sum(loss, dim=1)) + + +def FocalLossWithLogits(y_pred, y_true, alpha=0.25, gamma=2.0): + """""" + Calculates the Focal Loss using predicted logits (raw scores), automatically applying the sigmoid function. + + :param y_pred: (torch.Tensor) Predicted logits. + :param y_true: (torch.Tensor) Ground truth labels, may contain NaNs. + :param alpha: (float) Weighting factor for balancing positive and negative examples. Defaults to 0.25. + :param gamma: (float) Focusing parameter to scale the loss. Defaults to 2.0. + + :return: (torch.Tensor) Computed focal loss. + """""" + y_pred = torch.sigmoid(y_pred) + mask = ~torch.isnan(y_true) + y_pred = y_pred[mask] + y_true = y_true[mask] + loss = FocalLoss(y_pred, y_true, alpha=alpha, gamma=gamma) + return loss + + +def myCrossEntropyLoss(y_pred, y_true): + """""" + Calculates the cross-entropy loss between predictions and targets. + + :param y_pred: (torch.Tensor) Predicted logits or probabilities. + :param y_true: (torch.Tensor) Ground truth labels. + + :return: (torch.Tensor) Computed cross-entropy loss. + """""" + if y_pred.shape != y_true.shape: + y_true = y_true.flatten() + return nn.CrossEntropyLoss()(y_pred, y_true) +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/models/nnmodel.py",".py","13388","357","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os + +import joblib +import numpy as np +import torch +import torch.nn as nn +from torch.nn import functional as F +from torch.utils.data import Dataset + +from ..utils import logger +from .loss import FocalLossWithLogits, GHMC_Loss, MAEwithNan, myCrossEntropyLoss +from .unimol import UniMolModel +from .unimolv2 import UniMolV2Model + +NNMODEL_REGISTER = { + 'unimolv1': UniMolModel, + 'unimolv2': UniMolV2Model, +} + +LOSS_RREGISTER = { + 'classification': myCrossEntropyLoss, + 'multiclass': myCrossEntropyLoss, + 'regression': nn.MSELoss(), + 'multilabel_classification': { + 'bce': nn.BCEWithLogitsLoss(), + 'ghm': GHMC_Loss(bins=10, alpha=0.5), + 'focal': FocalLossWithLogits, + }, + 'multilabel_regression': MAEwithNan, +} + + +def classification_activation(x): + return F.softmax(x, dim=-1)[:, 1:] + + +def multiclass_activation(x): + return F.softmax(x, dim=-1) + + +def regression_activation(x): + return x + + +def multilabel_classification_activation(x): + return F.sigmoid(x) + + +def multilabel_regression_activation(x): + return x + + +ACTIVATION_FN = { + 'classification': classification_activation, + 'multiclass': multiclass_activation, + 'regression': regression_activation, + 'multilabel_classification': multilabel_classification_activation, + 'multilabel_regression': multilabel_regression_activation, +} +OUTPUT_DIM = { + 'classification': 2, + 'regression': 1, +} + + +class NNModel(object): + """"""A :class:`NNModel` class is responsible for initializing the model"""""" + + def __init__(self, data, trainer, **params): + """""" + Initializes the neural network model with the given data and parameters. + + :param data: (dict) Contains the dataset information, including features and target scaling. + :param trainer: (object) An instance of a training class, responsible for managing training processes. + :param params: Various additional parameters used for model configuration. + + The model is configured based on the task type and specific parameters provided. + """""" + self.data = data + self.num_classes = self.data['num_classes'] + self.target_scaler = self.data['target_scaler'] + self.features = data['unimol_input'] + self.model_name = params.get('model_name', 'unimolv1') + self.data_type = params.get('data_type', 'molecule') + self.loss_key = params.get('loss_key', None) + self.trainer = trainer + # self.splitter = self.trainer.splitter + self.model_params = params.copy() + self.task = params['task'] + if self.task in OUTPUT_DIM: + self.model_params['output_dim'] = OUTPUT_DIM[self.task] + elif self.task == 'multiclass': + self.model_params['output_dim'] = self.data['multiclass_cnt'] + else: + self.model_params['output_dim'] = self.num_classes + self.model_params['device'] = self.trainer.device + self.cv = dict() + self.metrics = self.trainer.metrics + if self.task == 'multilabel_classification': + if self.loss_key is None: + self.loss_key = 'focal' + self.loss_func = LOSS_RREGISTER[self.task][self.loss_key] + else: + self.loss_func = LOSS_RREGISTER[self.task] + self.activation_fn = ACTIVATION_FN[self.task] + self.save_path = self.trainer.save_path + self.trainer.set_seed(self.trainer.seed) + self.model = self._init_model(**self.model_params) + + def _init_model(self, model_name, **params): + """""" + Initializes the neural network model based on the provided model name and parameters. + + :param model_name: (str) The name of the model to initialize. + :param params: Additional parameters for model configuration. + + :return: An instance of the specified neural network model. + :raises ValueError: If the model name is not recognized. + """""" + if self.task in ['regression', 'multilabel_regression']: + params['pooler_dropout'] = 0 + logger.debug(""set pooler_dropout to 0 for regression task"") + else: + pass + freeze_layers = params.get('freeze_layers', None) + freeze_layers_reversed = params.get('freeze_layers_reversed', False) + if model_name in NNMODEL_REGISTER: + model = NNMODEL_REGISTER[model_name](**params) + if isinstance(freeze_layers, str): + freeze_layers = freeze_layers.replace(' ', '').split(',') + if isinstance(freeze_layers, list): + for layer_name, layer_param in model.named_parameters(): + should_freeze = any( + layer_name.startswith(freeze_layer) + for freeze_layer in freeze_layers + ) + layer_param.requires_grad = not ( + freeze_layers_reversed ^ should_freeze + ) + else: + raise ValueError('Unknown model: {}'.format(self.model_name)) + return model + + def collect_data(self, X, y, idx): + """""" + Collects and formats the training or validation data. + + :param X: (np.ndarray or dict) The input features, either as a numpy array or a dictionary of tensors. + :param y: (np.ndarray) The target values as a numpy array. + :param idx: Indices to select the specific data samples. + + :return: A tuple containing processed input data and target values. + :raises ValueError: If X is neither a numpy array nor a dictionary. + """""" + assert isinstance(y, np.ndarray), 'y must be numpy array' + if isinstance(X, np.ndarray): + return torch.from_numpy(X[idx]).float(), torch.from_numpy(y[idx]) + elif isinstance(X, dict): + return {k: v[idx] for k, v in X.items()}, torch.from_numpy(y[idx]) + else: + raise ValueError('X must be numpy array or dict') + + def run(self): + """""" + Executes the training process of the model. This involves data preparation, + model training, validation, and computing metrics for each fold in cross-validation. + """""" + logger.info(""start training Uni-Mol:{}"".format(self.model_name)) + X = np.asarray(self.features) + y = np.asarray(self.data['target']) + group = ( + np.asarray(self.data['group']) if self.data['group'] is not None else None + ) + if self.task == 'classification': + y_pred = np.zeros_like(y.reshape(y.shape[0], self.num_classes)).astype( + float + ) + else: + y_pred = np.zeros((y.shape[0], self.model_params['output_dim'])) + for fold, (tr_idx, te_idx) in enumerate(self.data['split_nfolds']): + X_train, y_train = X[tr_idx], y[tr_idx] + X_valid, y_valid = X[te_idx], y[te_idx] + traindataset = NNDataset(X_train, y_train) + validdataset = NNDataset(X_valid, y_valid) + if fold > 0: + # need to initalize model for next fold training + self.model = self._init_model(**self.model_params) + + # TODO: move the following code to model.load_pretrained_weights + if self.model_params.get('load_model_dir', None) is not None: + load_model_path = os.path.join( + self.model_params['load_model_dir'], f'model_{fold}.pth' + ) + model_dict = torch.load( + load_model_path, map_location=self.model_params['device'] + )[""model_state_dict""] + if ( + model_dict['classification_head.out_proj.weight'].shape[0] + != self.model.output_dim + ): + current_model_dict = self.model.state_dict() + model_dict = { + k: v + for k, v in model_dict.items() + if k in current_model_dict + and 'classification_head.out_proj' not in k + } + current_model_dict.update(model_dict) + logger.info( + ""The output_dim of the model is different from the loaded model, only load the common part of the model"" + ) + self.model.load_state_dict(model_dict, strict=False) + else: + self.model.load_state_dict(model_dict) + + logger.info(""load model success from {}"".format(load_model_path)) + _y_pred = self.trainer.fit_predict( + self.model, + traindataset, + validdataset, + self.loss_func, + self.activation_fn, + self.save_path, + fold, + self.target_scaler, + ) + y_pred[te_idx] = _y_pred + + if 'multiclass_cnt' in self.data: + label_cnt = self.data['multiclass_cnt'] + else: + label_cnt = None + + logger.info( + ""fold {0}, result {1}"".format( + fold, + self.metrics.cal_metric( + self.data['target_scaler'].inverse_transform(y_valid), + self.data['target_scaler'].inverse_transform(_y_pred), + label_cnt=label_cnt, + ), + ) + ) + + self.cv['pred'] = y_pred + self.cv['metric'] = self.metrics.cal_metric( + self.data['target_scaler'].inverse_transform(y), + self.data['target_scaler'].inverse_transform(self.cv['pred']), + ) + self.dump(self.cv['pred'], self.save_path, 'cv.data') + self.dump(self.cv['metric'], self.save_path, 'metric.result') + logger.info(""Uni-Mol metrics score: \n{}"".format(self.cv['metric'])) + logger.info(""Uni-Mol & Metric result saved!"") + + def dump(self, data, dir, name): + """""" + Saves the specified data to a file. + + :param data: The data to be saved. + :param dir: (str) The directory where the data will be saved. + :param name: (str) The name of the file to save the data. + """""" + path = os.path.join(dir, name) + if not os.path.exists(dir): + os.makedirs(dir) + joblib.dump(data, path) + + def evaluate(self, trainer=None, checkpoints_path=None): + """""" + Evaluates the model by making predictions on the test set and averaging the results. + + :param trainer: An optional trainer instance to use for prediction. + :param checkpoints_path: (str) The path to the saved model checkpoints. + """""" + logger.info(""start predict NNModel:{}"".format(self.model_name)) + testdataset = NNDataset(self.features, np.asarray(self.data['target'])) + for fold in range(self.data['kfold']): + _y_pred, _, __ = trainer.predict( + self.model, + testdataset, + self.loss_func, + self.activation_fn, + self.save_path, + fold, + self.target_scaler, + epoch=1, + load_model=True, + ) + if fold == 0: + y_pred = np.zeros_like(_y_pred) + y_pred += _y_pred + y_pred /= self.data['kfold'] + self.cv['test_pred'] = y_pred + + def count_parameters(self, model): + """""" + Counts the number of trainable parameters in the model. + + :param model: The model whose parameters are to be counted. + + :return: (int) The number of trainable parameters. + """""" + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + +def NNDataset(data, label=None): + """""" + Creates a dataset suitable for use with PyTorch models. + + :param data: The input data. + :param label: Optional labels corresponding to the input data. + + :return: An instance of TorchDataset. + """""" + return TorchDataset(data, label) + + +class TorchDataset(Dataset): + """""" + A custom dataset class for PyTorch that handles data and labels. This class is compatible with PyTorch's Dataset interface + and can be used with a DataLoader for efficient batch processing. It's designed to work with both numpy arrays and PyTorch tensors. + """""" + + def __init__(self, data, label=None): + """""" + Initializes the dataset with data and labels. + + :param data: The input data. + :param label: The target labels for the input data. + """""" + self.data = data + self.label = label if label is not None else np.zeros((len(data), 1)) + + def __getitem__(self, idx): + """""" + Retrieves the data item and its corresponding label at the specified index. + + :param idx: (int) The index of the data item to retrieve. + + :return: A tuple containing the data item and its label. + """""" + return self.data[idx], self.label[idx] + + def __len__(self): + """""" + Returns the total number of items in the dataset. + + :return: (int) The size of the dataset. + """""" + return len(self.data) +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/models/unimol.py",".py","23801","665","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os + +# import argparse +import pathlib + +import torch +import torch.nn as nn +import torch.nn.functional as F +from addict import Dict +import numpy as np + +from ..config import MODEL_CONFIG +from ..data import Dictionary +from ..utils import logger, pad_1d_tokens, pad_2d, pad_coords +from ..weights import get_weight_dir, weight_download +from .transformers import TransformerEncoderWithPair + +BACKBONE = { + 'transformer': TransformerEncoderWithPair, +} + + +class UniMolModel(nn.Module): + """""" + UniMolModel is a specialized model for molecular, protein, crystal, or MOF (Metal-Organic Frameworks) data. + It dynamically configures its architecture based on the type of data it is intended to work with. The model + supports multiple data types and incorporates various architecture configurations and pretrained weights. + + Attributes: + - output_dim: The dimension of the output layer. + - data_type: The type of data the model is designed to handle. + - remove_hs: Flag to indicate whether hydrogen atoms are removed in molecular data. + - pretrain_path: Path to the pretrained model weights. + - dictionary: The dictionary object used for tokenization and encoding. + - mask_idx: Index of the mask token in the dictionary. + - padding_idx: Index of the padding token in the dictionary. + - embed_tokens: Embedding layer for token embeddings. + - encoder: Transformer encoder backbone of the model. + - gbf_proj, gbf: Layers for Gaussian basis functions or numerical embeddings. + - classification_head: The final classification head of the model. + """""" + + def __init__( + self, + output_dim=2, + data_type='molecule', + pretrained_model_path=None, + pretrained_dict_path=None, + **params, + ): + """"""Initializes the UniMolModel with specified parameters and data type. + + :param output_dim: (int) The number of output dimensions (classes). + :param data_type: (str) The type of data (e.g., 'molecule', 'protein'). + :param params: Additional parameters for model configuration. + :param pretrained_model_path: (str, optional) Path to a custom + pretrained model checkpoint. If ``None`` the default weights shipped + with ``unimol_tools`` will be used. + :param pretrained_dict_path: (str, optional) Path to the token + dictionary corresponding to ``pretrained_model_path``. If ``None`` + and ``pretrained_model_path`` is provided, it is assumed that a file + named ``dict.txt`` exists in the same directory as the checkpoint. + """""" + + super().__init__() + if data_type == 'molecule': + self.args = molecule_architecture() + elif data_type == 'oled': + self.args = oled_architecture() + elif data_type == 'protein': + self.args = protein_architecture() + elif data_type == 'crystal': + self.args = crystal_architecture() + elif data_type == 'pocket': + self.args = molecule_architecture() + else: + raise ValueError('Current not support data type: {}'.format(data_type)) + self.output_dim = output_dim + self.data_type = data_type + self.remove_hs = params.get('remove_hs', False) + if data_type == 'molecule': + name = ""no_h"" if self.remove_hs else ""all_h"" + name = data_type + '_' + name + else: + name = data_type + + if pretrained_model_path is not None: + self.pretrain_path = pretrained_model_path + if pretrained_dict_path is None: + pretrained_dict_path = os.path.join( + os.path.dirname(pretrained_model_path), ""dict.txt"" + ) + self.dictionary = Dictionary.load(pretrained_dict_path) + else: + weight_dir = get_weight_dir() + if not os.path.exists( + os.path.join(weight_dir, MODEL_CONFIG['weight'][name]) + ): + weight_download(MODEL_CONFIG['weight'][name], weight_dir) + if not os.path.exists( + os.path.join(weight_dir, MODEL_CONFIG['dict'][name]) + ): + weight_download(MODEL_CONFIG['dict'][name], weight_dir) + self.pretrain_path = os.path.join( + weight_dir, MODEL_CONFIG['weight'][name] + ) + self.dictionary = Dictionary.load( + os.path.join(weight_dir, MODEL_CONFIG['dict'][name]) + ) + self.mask_idx = self.dictionary.add_symbol(""[MASK]"", is_special=True) + self.padding_idx = self.dictionary.pad() + self.embed_tokens = nn.Embedding( + len(self.dictionary), self.args.encoder_embed_dim, self.padding_idx + ) + self.encoder = BACKBONE[self.args.backbone]( + encoder_layers=self.args.encoder_layers, + embed_dim=self.args.encoder_embed_dim, + ffn_embed_dim=self.args.encoder_ffn_embed_dim, + attention_heads=self.args.encoder_attention_heads, + emb_dropout=self.args.emb_dropout, + dropout=self.args.dropout, + attention_dropout=self.args.attention_dropout, + activation_dropout=self.args.activation_dropout, + max_seq_len=self.args.max_seq_len, + activation_fn=self.args.activation_fn, + no_final_head_layer_norm=self.args.delta_pair_repr_norm_loss < 0, + ) + K = 128 + n_edge_type = len(self.dictionary) * len(self.dictionary) + self.gbf_proj = NonLinearHead( + K, self.args.encoder_attention_heads, self.args.activation_fn + ) + if self.args.kernel == 'gaussian': + self.gbf = GaussianLayer(K, n_edge_type) + else: + self.gbf = NumericalEmbed(K, n_edge_type) + """""" + # To be deprecated in the future. + self.classification_head = ClassificationHead( + input_dim=self.args.encoder_embed_dim, + inner_dim=self.args.encoder_embed_dim, + num_classes=self.output_dim, + activation_fn=self.args.pooler_activation_fn, + pooler_dropout=self.args.pooler_dropout, + ) + """""" + if 'pooler_dropout' in params: + self.args.pooler_dropout = params['pooler_dropout'] + self.classification_head = LinearHead( + input_dim=self.args.encoder_embed_dim, + num_classes=self.output_dim, + pooler_dropout=self.args.pooler_dropout, + ) + self.load_pretrained_weights(path=self.pretrain_path) + + def load_pretrained_weights(self, path, strict=False): + """""" + Loads pretrained weights into the model. + + :param path: (str) Path to the pretrained weight file. + """""" + if path is not None: + logger.info(""Loading pretrained weights from {}"".format(path)) + state_dict = torch.load(path, map_location=lambda storage, loc: storage) + if 'model' in state_dict: + state_dict = state_dict['model'] + elif 'model_state_dict' in state_dict: + state_dict = state_dict['model_state_dict'] + try: + self.load_state_dict(state_dict, strict=strict) + except RuntimeError as e: + if 'classification_head.dense.weight' in state_dict: + self.classification_head = ClassificationHead( + input_dim=self.args.encoder_embed_dim, + inner_dim=self.args.encoder_embed_dim, + num_classes=self.output_dim, + activation_fn=self.args.pooler_activation_fn, + pooler_dropout=self.args.pooler_dropout, + ) + self.load_state_dict(state_dict, strict=strict) + logger.warning( + ""This model is trained with the previous version. The classification_head is reset to previous version to load the model. This will be deprecated in the future. We recommend using the latest version of the model."" + ) + else: + raise e + + @classmethod + def build_model(cls, args): + """""" + Class method to build a new instance of the UniMolModel. + + :param args: Arguments for model configuration. + :return: An instance of UniMolModel. + """""" + return cls(args) + + def forward( + self, + src_tokens, + src_distance, + src_coord, + src_edge_type, + return_repr=False, + return_atomic_reprs=False, + **kwargs + ): + """""" + Defines the forward pass of the model. + + :param src_tokens: Tokenized input data. + :param src_distance: Additional molecular features. + :param src_coord: Additional molecular features. + :param src_edge_type: Additional molecular features. + :param gas_id: Optional environmental features for MOFs. + :param gas_attr: Optional environmental features for MOFs. + :param pressure: Optional environmental features for MOFs. + :param temperature: Optional environmental features for MOFs. + :param return_repr: Flags to return intermediate representations. + :param return_atomic_reprs: Flags to return intermediate representations. + + :return: Output logits or requested intermediate representations. + """""" + padding_mask = src_tokens.eq(self.padding_idx) + if not padding_mask.any(): + padding_mask = None + x = self.embed_tokens(src_tokens) + + def get_dist_features(dist, et): + n_node = dist.size(-1) + gbf_feature = self.gbf(dist, et) + gbf_result = self.gbf_proj(gbf_feature) + graph_attn_bias = gbf_result + graph_attn_bias = graph_attn_bias.permute(0, 3, 1, 2).contiguous() + graph_attn_bias = graph_attn_bias.view(-1, n_node, n_node) + return graph_attn_bias + + graph_attn_bias = get_dist_features(src_distance, src_edge_type) + ( + encoder_rep, + _, + _, + _, + _, + ) = self.encoder(x, padding_mask=padding_mask, attn_mask=graph_attn_bias) + cls_repr = encoder_rep[:, 0, :] # CLS token repr + all_repr = encoder_rep[:, :, :] # all token repr + + if return_repr: + if return_atomic_reprs: + filtered_tensors = [] + filtered_coords = [] + for tokens, coord in zip(src_tokens, src_coord): + filtered_tensor = tokens[ + (tokens != 0) & (tokens != 1) & (tokens != 2) + ] # filter out BOS(0), EOS(1), PAD(2) + filtered_coord = coord[(tokens != 0) & (tokens != 1) & (tokens != 2)] + filtered_tensors.append(filtered_tensor) + filtered_coords.append(filtered_coord) + + lengths = [ + len(filtered_tensor) for filtered_tensor in filtered_tensors + ] # Compute the lengths of the filtered tensors + + cls_atomic_reprs = [] + atomic_symbols = [] + for i in range(len(all_repr)): + atomic_reprs = encoder_rep[i, 1 : lengths[i] + 1, :] + atomic_symbol = [] + for atomic_num in filtered_tensors[i]: + atomic_symbol.append(self.dictionary.symbols[atomic_num]) + atomic_symbols.append(atomic_symbol) + cls_atomic_reprs.append(atomic_reprs) + return { + 'cls_repr': cls_repr, + 'atomic_symbol': atomic_symbols, + 'atomic_coords': filtered_coords, + 'atomic_reprs': cls_atomic_reprs, + } + else: + return cls_repr + + logits = self.classification_head(cls_repr) + return logits + + def batch_collate_fn(self, samples): + """""" + Custom collate function for batch processing non-MOF data. + + :param samples: A list of sample data. + + :return: A tuple containing a batch dictionary and labels. + """""" + batch = {} + for k in samples[0][0].keys(): + if k == 'src_coord': + v = pad_coords( + [torch.tensor(s[0][k]).float() for s in samples], pad_idx=0.0 + ) + elif k == 'src_edge_type': + v = pad_2d( + [torch.tensor(s[0][k]).long() for s in samples], + pad_idx=self.padding_idx, + ) + elif k == 'src_distance': + v = pad_2d( + [torch.tensor(s[0][k]).float() for s in samples], pad_idx=0.0 + ) + elif k == 'src_tokens': + v = pad_1d_tokens( + [torch.tensor(s[0][k]).long() for s in samples], + pad_idx=self.padding_idx, + ) + batch[k] = v + try: + label = torch.tensor(np.array([s[1] for s in samples])) + except: + label = None + return batch, label + + +class LinearHead(nn.Module): + """"""Linear head."""""" + + def __init__( + self, + input_dim, + num_classes, + pooler_dropout, + ): + """""" + Initialize the Linear head. + + :param input_dim: Dimension of input features. + :param num_classes: Number of classes for output. + """""" + super().__init__() + self.out_proj = nn.Linear(input_dim, num_classes) + self.dropout = nn.Dropout(p=pooler_dropout) + + def forward(self, features, **kwargs): + """""" + Forward pass for the Linear head. + + :param features: Input features. + + :return: Output from the Linear head. + """""" + x = features + x = self.dropout(x) + x = self.out_proj(x) + return x + + +class ClassificationHead(nn.Module): + """"""Head for sentence-level classification tasks."""""" + + def __init__( + self, + input_dim, + inner_dim, + num_classes, + activation_fn, + pooler_dropout, + ): + """""" + Initialize the classification head. + + :param input_dim: Dimension of input features. + :param inner_dim: Dimension of the inner layer. + :param num_classes: Number of classes for classification. + :param activation_fn: Activation function name. + :param pooler_dropout: Dropout rate for the pooling layer. + """""" + super().__init__() + self.dense = nn.Linear(input_dim, inner_dim) + self.activation_fn = get_activation_fn(activation_fn) + self.dropout = nn.Dropout(p=pooler_dropout) + self.out_proj = nn.Linear(inner_dim, num_classes) + + def forward(self, features, **kwargs): + """""" + Forward pass for the classification head. + + :param features: Input features for classification. + + :return: Output from the classification head. + """""" + x = features + x = self.dropout(x) + x = self.dense(x) + x = self.activation_fn(x) + x = self.dropout(x) + x = self.out_proj(x) + return x + + +class NonLinearHead(nn.Module): + """""" + A neural network module used for simple classification tasks. It consists of a two-layered linear network + with a nonlinear activation function in between. + + Attributes: + - linear1: The first linear layer. + - linear2: The second linear layer that outputs to the desired dimensions. + - activation_fn: The nonlinear activation function. + """""" + + def __init__( + self, + input_dim, + out_dim, + activation_fn, + hidden=None, + ): + """""" + Initializes the NonLinearHead module. + + :param input_dim: Dimension of the input features. + :param out_dim: Dimension of the output. + :param activation_fn: The activation function to use. + :param hidden: Dimension of the hidden layer; defaults to the same as input_dim if not provided. + """""" + super().__init__() + hidden = input_dim if not hidden else hidden + self.linear1 = nn.Linear(input_dim, hidden) + self.linear2 = nn.Linear(hidden, out_dim) + self.activation_fn = get_activation_fn(activation_fn) + + def forward(self, x): + """""" + Forward pass of the NonLinearHead. + + :param x: Input tensor to the module. + + :return: Tensor after passing through the network. + """""" + x = self.linear1(x) + x = self.activation_fn(x) + x = self.linear2(x) + return x + + +@torch.jit.script +def gaussian(x, mean, std): + """""" + Gaussian function implemented for PyTorch tensors. + + :param x: The input tensor. + :param mean: The mean for the Gaussian function. + :param std: The standard deviation for the Gaussian function. + + :return: The output tensor after applying the Gaussian function. + """""" + pi = 3.14159 + a = (2 * pi) ** 0.5 + return torch.exp(-0.5 * (((x - mean) / std) ** 2)) / (a * std) + + +def get_activation_fn(activation): + """"""Returns the activation function corresponding to `activation`"""""" + + if activation == ""relu"": + return F.relu + elif activation == ""gelu"": + return F.gelu + elif activation == ""tanh"": + return torch.tanh + elif activation == ""linear"": + return lambda x: x + else: + raise RuntimeError(""--activation-fn {} not supported"".format(activation)) + + +class GaussianLayer(nn.Module): + """""" + A neural network module implementing a Gaussian layer, useful in graph neural networks. + + Attributes: + - K: Number of Gaussian kernels. + - means, stds: Embeddings for the means and standard deviations of the Gaussian kernels. + - mul, bias: Embeddings for scaling and bias parameters. + """""" + + def __init__(self, K=128, edge_types=1024): + """""" + Initializes the GaussianLayer module. + + :param K: Number of Gaussian kernels. + :param edge_types: Number of different edge types to consider. + + :return: An instance of the configured Gaussian kernel and edge types. + """""" + super().__init__() + self.K = K + self.means = nn.Embedding(1, K) + self.stds = nn.Embedding(1, K) + self.mul = nn.Embedding(edge_types, 1) + self.bias = nn.Embedding(edge_types, 1) + nn.init.uniform_(self.means.weight, 0, 3) + nn.init.uniform_(self.stds.weight, 0, 3) + nn.init.constant_(self.bias.weight, 0) + nn.init.constant_(self.mul.weight, 1) + + def forward(self, x, edge_type): + """""" + Forward pass of the GaussianLayer. + + :param x: Input tensor representing distances or other features. + :param edge_type: Tensor indicating types of edges in the graph. + + :return: Tensor transformed by the Gaussian layer. + """""" + mul = self.mul(edge_type).type_as(x) + bias = self.bias(edge_type).type_as(x) + x = mul * x.unsqueeze(-1) + bias + x = x.expand(-1, -1, -1, self.K) + mean = self.means.weight.float().view(-1) + std = self.stds.weight.float().view(-1).abs() + 1e-5 + return gaussian(x.float(), mean, std).type_as(self.means.weight) + + +class NumericalEmbed(nn.Module): + """""" + Numerical embedding module, typically used for embedding edge features in graph neural networks. + + Attributes: + - K: Output dimension for embeddings. + - mul, bias, w_edge: Embeddings for transformation parameters. + - proj: Projection layer to transform inputs. + - ln: Layer normalization. + """""" + + def __init__(self, K=128, edge_types=1024, activation_fn='gelu'): + """""" + Initializes the NonLinearHead. + + :param input_dim: The input dimension of the first layer. + :param out_dim: The output dimension of the second layer. + :param activation_fn: The activation function to use. + :param hidden: The dimension of the hidden layer; defaults to input_dim if not specified. + """""" + super().__init__() + self.K = K + self.mul = nn.Embedding(edge_types, 1) + self.bias = nn.Embedding(edge_types, 1) + self.w_edge = nn.Embedding(edge_types, K) + + self.proj = NonLinearHead(1, K, activation_fn, hidden=2 * K) + self.ln = nn.LayerNorm(K) + + nn.init.constant_(self.bias.weight, 0) + nn.init.constant_(self.mul.weight, 1) + nn.init.kaiming_normal_(self.w_edge.weight) + + def forward(self, x, edge_type): # edge_type, atoms + """""" + Forward pass of the NonLinearHead. + + :param x: Input tensor to the classification head. + + :return: The output tensor after passing through the layers. + """""" + mul = self.mul(edge_type).type_as(x) + bias = self.bias(edge_type).type_as(x) + w_edge = self.w_edge(edge_type).type_as(x) + edge_emb = w_edge * torch.sigmoid(mul * x.unsqueeze(-1) + bias) + + edge_proj = x.unsqueeze(-1).type_as(self.mul.weight) + edge_proj = self.proj(edge_proj) + edge_proj = self.ln(edge_proj) + + h = edge_proj + edge_emb + h = h.type_as(self.mul.weight) + return h + + +def molecule_architecture(): + args = Dict() + args.encoder_layers = 15 + args.encoder_embed_dim = 512 + args.encoder_ffn_embed_dim = 2048 + args.encoder_attention_heads = 64 + args.dropout = 0.1 + args.emb_dropout = 0.1 + args.attention_dropout = 0.1 + args.activation_dropout = 0.0 + args.pooler_dropout = 0.2 + args.max_seq_len = 512 + args.activation_fn = ""gelu"" + args.pooler_activation_fn = ""tanh"" + args.post_ln = False + args.backbone = ""transformer"" + args.kernel = ""gaussian"" + args.delta_pair_repr_norm_loss = -1.0 + return args + + +def protein_architecture(): + args = Dict() + args.encoder_layers = 15 + args.encoder_embed_dim = 512 + args.encoder_ffn_embed_dim = 2048 + args.encoder_attention_heads = 64 + args.dropout = 0.1 + args.emb_dropout = 0.1 + args.attention_dropout = 0.1 + args.activation_dropout = 0.0 + args.pooler_dropout = 0.2 + args.max_seq_len = 512 + args.activation_fn = ""gelu"" + args.pooler_activation_fn = ""tanh"" + args.post_ln = False + args.backbone = ""transformer"" + args.kernel = ""gaussian"" + args.delta_pair_repr_norm_loss = -1.0 + return args + + +def crystal_architecture(): + args = Dict() + args.encoder_layers = 8 + args.encoder_embed_dim = 512 + args.encoder_ffn_embed_dim = 2048 + args.encoder_attention_heads = 64 + args.dropout = 0.1 + args.emb_dropout = 0.1 + args.attention_dropout = 0.1 + args.activation_dropout = 0.0 + args.pooler_dropout = 0.0 + args.max_seq_len = 1024 + args.activation_fn = ""gelu"" + args.pooler_activation_fn = ""tanh"" + args.post_ln = False + args.backbone = ""transformer"" + args.kernel = ""linear"" + args.delta_pair_repr_norm_loss = -1.0 + return args + + +def oled_architecture(): + args = Dict() + args.encoder_layers = 8 + args.encoder_embed_dim = 512 + args.encoder_ffn_embed_dim = 2048 + args.encoder_attention_heads = 64 + args.dropout = 0.1 + args.emb_dropout = 0.1 + args.attention_dropout = 0.1 + args.activation_dropout = 0.0 + args.pooler_dropout = 0.0 + args.max_seq_len = 1024 + args.activation_fn = ""gelu"" + args.pooler_activation_fn = ""tanh"" + args.post_ln = False + args.backbone = ""transformer"" + args.kernel = ""linear"" + args.delta_pair_repr_norm_loss = -1.0 + return args +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/models/__init__.py",".py","57","2","from .nnmodel import NNModel, UniMolModel, UniMolV2Model +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/models/unimolv2.py",".py","25235","717","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os +import pathlib + +import torch +import torch.nn as nn +import torch.nn.functional as F +from addict import Dict +import numpy as np + +from ..config import MODEL_CONFIG_V2 +from ..utils import logger, pad_1d_tokens, pad_2d, pad_coords +from ..weights import get_weight_dir, weight_download_v2 +from .transformersv2 import ( + AtomFeature, + EdgeFeature, + MovementPredictionHead, + SE3InvariantKernel, + TransformerEncoderWithPairV2, +) + +BACKBONE = { + 'transformer': TransformerEncoderWithPairV2, +} + + +class UniMolV2Model(nn.Module): + """""" + UniMolModel is a specialized model for molecular, protein, crystal, or MOF (Metal-Organic Frameworks) data. + It dynamically configures its architecture based on the type of data it is intended to work with. The model + supports multiple data types and incorporates various architecture configurations and pretrained weights. + + Attributes: + - output_dim: The dimension of the output layer. + - data_type: The type of data the model is designed to handle. + - remove_hs: Flag to indicate whether hydrogen atoms are removed in molecular data. + - pretrain_path: Path to the pretrained model weights. + - dictionary: The dictionary object used for tokenization and encoding. + - mask_idx: Index of the mask token in the dictionary. + - padding_idx: Index of the padding token in the dictionary. + - embed_tokens: Embedding layer for token embeddings. + - encoder: Transformer encoder backbone of the model. + - gbf_proj, gbf: Layers for Gaussian basis functions or numerical embeddings. + - classification_head: The final classification head of the model. + """""" + + def __init__( + self, + output_dim=2, + model_size='84m', + pretrained_model_path=None, + **params, + ): + """"""Initializes the UniMolModel with specified parameters and data type. + + :param output_dim: (int) The number of output dimensions (classes). + :param model_size: (str) The size identifier for UniMolV2. + :param pretrained_model_path: (str, optional) Path to a custom + pretrained model checkpoint. If ``None`` the default weights shipped + with ``unimol_tools`` will be used. + :param params: Additional parameters for model configuration. + """""" + super().__init__() + + self.args = molecule_architecture(model_size=model_size) + self.output_dim = output_dim + self.model_size = model_size + self.remove_hs = params.get('remove_hs', False) + + name = model_size + if pretrained_model_path is not None: + self.pretrain_path = pretrained_model_path + else: + weight_dir = get_weight_dir() + if not os.path.exists( + os.path.join(weight_dir, MODEL_CONFIG_V2['weight'][name]) + ): + weight_download_v2(MODEL_CONFIG_V2['weight'][name], weight_dir) + + self.pretrain_path = os.path.join( + weight_dir, MODEL_CONFIG_V2['weight'][name] + ) + + self.token_num = 128 + self.padding_idx = 0 + self.mask_idx = 127 + self.embed_tokens = nn.Embedding( + self.token_num, self.args.encoder_embed_dim, self.padding_idx + ) + + self.encoder = BACKBONE[self.args.backbone]( + num_encoder_layers=self.args.num_encoder_layers, + embedding_dim=self.args.encoder_embed_dim, + pair_dim=self.args.pair_embed_dim, + pair_hidden_dim=self.args.pair_hidden_dim, + ffn_embedding_dim=self.args.ffn_embedding_dim, + num_attention_heads=self.args.num_attention_heads, + dropout=self.args.dropout, + attention_dropout=self.args.attention_dropout, + activation_dropout=self.args.activation_dropout, + activation_fn=self.args.activation_fn, + droppath_prob=self.args.droppath_prob, + pair_dropout=self.args.pair_dropout, + ) + + num_atom = 512 + num_degree = 128 + num_edge = 64 + num_pair = 512 + num_spatial = 512 + + K = 128 + n_edge_type = 1 + + self.atom_feature = AtomFeature( + num_atom=num_atom, + num_degree=num_degree, + hidden_dim=self.args.encoder_embed_dim, + ) + + self.edge_feature = EdgeFeature( + pair_dim=self.args.pair_embed_dim, + num_edge=num_edge, + num_spatial=num_spatial, + ) + + self.se3_invariant_kernel = SE3InvariantKernel( + pair_dim=self.args.pair_embed_dim, + num_pair=num_pair, + num_kernel=K, + std_width=self.args.gaussian_std_width, + start=self.args.gaussian_mean_start, + stop=self.args.gaussian_mean_stop, + ) + + self.movement_pred_head = MovementPredictionHead( + self.args.encoder_embed_dim, + self.args.pair_embed_dim, + self.args.encoder_attention_heads, + ) + + self.classification_heads = nn.ModuleDict() + self.dtype = torch.float32 + + """""" + # To be deprecated in the future. + self.classification_head = ClassificationHead( + input_dim=self.args.encoder_embed_dim, + inner_dim=self.args.encoder_embed_dim, + num_classes=self.output_dim, + activation_fn=self.args.pooler_activation_fn, + pooler_dropout=self.args.pooler_dropout, + ) + """""" + if 'pooler_dropout' in params: + self.args.pooler_dropout = params['pooler_dropout'] + self.classification_head = LinearHead( + input_dim=self.args.encoder_embed_dim, + num_classes=self.output_dim, + pooler_dropout=self.args.pooler_dropout, + ) + self.load_pretrained_weights(path=self.pretrain_path) + + def load_pretrained_weights(self, path, strict=False): + """""" + Loads pretrained weights into the model. + + :param path: (str) Path to the pretrained weight file. + """""" + if path is not None: + logger.info(""Loading pretrained weights from {}"".format(path)) + state_dict = torch.load(path, map_location=lambda storage, loc: storage) + if 'model' in state_dict: + state_dict = state_dict['model'] + elif 'model_state_dict' in state_dict: + state_dict = state_dict['model_state_dict'] + try: + self.load_state_dict(state_dict, strict=strict) + except RuntimeError as e: + if 'classification_head.dense.weight' in state_dict: + self.classification_head = ClassificationHead( + input_dim=self.args.encoder_embed_dim, + inner_dim=self.args.encoder_embed_dim, + num_classes=self.output_dim, + activation_fn=self.args.pooler_activation_fn, + pooler_dropout=self.args.pooler_dropout, + ) + self.load_state_dict(state_dict, strict=strict) + logger.warning( + ""This model is trained with the previous version. The classification_head is reset to previous version to load the model. This will be deprecated in the future. We recommend using the latest version of the model."" + ) + else: + raise e + + @classmethod + def build_model(cls, args): + """""" + Class method to build a new instance of the UniMolModel. + + :param args: Arguments for model configuration. + :return: An instance of UniMolModel. + """""" + return cls(args) + + #'atom_feat', 'atom_mask', 'edge_feat', 'shortest_path', 'degree', 'pair_type', 'attn_bias', 'src_tokens' + def forward( + self, + atom_feat, + atom_mask, + edge_feat, + shortest_path, + degree, + pair_type, + attn_bias, + src_tokens, + src_coord, + return_repr=False, + return_atomic_reprs=False, + **kwargs + ): + + pos = src_coord + + n_mol, n_atom = atom_feat.shape[:2] + token_feat = self.embed_tokens(src_tokens) + x = self.atom_feature({'atom_feat': atom_feat, 'degree': degree}, token_feat) + + dtype = self.dtype + + x = x.type(dtype) + + attn_mask = attn_bias.clone() + attn_bias = torch.zeros_like(attn_mask) + attn_mask = attn_mask.unsqueeze(1).repeat( + 1, self.args.encoder_attention_heads, 1, 1 + ) + attn_bias = attn_bias.unsqueeze(-1).repeat(1, 1, 1, self.args.pair_embed_dim) + attn_bias = self.edge_feature( + {'shortest_path': shortest_path, 'edge_feat': edge_feat}, attn_bias + ) + attn_mask = attn_mask.type(self.dtype) + + atom_mask_cls = torch.cat( + [ + torch.ones(n_mol, 1, device=atom_mask.device, dtype=atom_mask.dtype), + atom_mask, + ], + dim=1, + ).type(self.dtype) + + pair_mask = atom_mask_cls.unsqueeze(-1) * atom_mask_cls.unsqueeze(-2) + + def one_block(x, pos, return_x=False): + delta_pos = pos.unsqueeze(1) - pos.unsqueeze(2) + dist = delta_pos.norm(dim=-1) + attn_bias_3d = self.se3_invariant_kernel(dist.detach(), pair_type) + new_attn_bias = attn_bias.clone() + new_attn_bias[:, 1:, 1:, :] = new_attn_bias[:, 1:, 1:, :] + attn_bias_3d + new_attn_bias = new_attn_bias.type(dtype) + x, pair = self.encoder( + x, + new_attn_bias, + atom_mask=atom_mask_cls, + pair_mask=pair_mask, + attn_mask=attn_mask, + ) + node_output = self.movement_pred_head( + x[:, 1:, :], + pair[:, 1:, 1:, :], + attn_mask[:, :, 1:, 1:], + delta_pos.detach(), + ) + if return_x: + return x, pair, pos + node_output + else: + return pos + node_output + + x, pair, pos = one_block(x, pos, return_x=True) + cls_repr = x[:, 0, :] # CLS token repr + all_repr = x[:, :, :] # all token repr + + if return_repr: + if return_atomic_reprs: + filtered_tensors = [] + filtered_coords = [] + + for tokens, coord in zip(src_tokens, src_coord): + filtered_tensor = tokens[ + (tokens != 0) & (tokens != 1) & (tokens != 2) + ] # filter out BOS(0), EOS(1), PAD(2) + filtered_coord = coord[(tokens != 0) & (tokens != 1) & (tokens != 2)] + filtered_tensors.append(filtered_tensor) + filtered_coords.append(filtered_coord) + + lengths = [ + len(filtered_tensor) for filtered_tensor in filtered_tensors + ] # Compute the lengths of the filtered tensors + + cls_atomic_reprs = [] + atomic_symbols = [] + for i in range(len(all_repr)): + atomic_reprs = x[i, 1 : lengths[i] + 1, :] + atomic_symbol = filtered_tensors[i] + atomic_symbols.append(atomic_symbol) + cls_atomic_reprs.append(atomic_reprs) + return { + 'cls_repr': cls_repr, + 'atomic_symbol': atomic_symbols, + 'atomic_coords': filtered_coords, + 'atomic_reprs': cls_atomic_reprs, + } + else: + return cls_repr + + logits = self.classification_head(cls_repr) + return logits + + def register_classification_head( + self, name, num_classes=None, inner_dim=None, **kwargs + ): + """"""Register a classification head."""""" + if name in self.classification_heads: + prev_num_classes = self.classification_heads[name].out_proj.out_features + prev_inner_dim = self.classification_heads[name].dense.out_features + if num_classes != prev_num_classes or inner_dim != prev_inner_dim: + logger.warning( + 're-registering head ""{}"" with num_classes {} (prev: {}) ' + ""and inner_dim {} (prev: {})"".format( + name, num_classes, prev_num_classes, inner_dim, prev_inner_dim + ) + ) + self.classification_heads[name] = ClassificationHead( + input_dim=self.args.encoder_embed_dim, + inner_dim=inner_dim or self.args.encoder_embed_dim, + num_classes=num_classes, + activation_fn=self.args.pooler_activation_fn, + pooler_dropout=self.args.pooler_dropout, + ) + + def set_num_updates(self, num_updates): + """"""State from trainer to pass along to model at every update."""""" + self._num_updates = num_updates + + def get_num_updates(self): + return self._num_updates + + def batch_collate_fn(self, samples): + """""" + Custom collate function for batch processing non-MOF data. + + :param samples: A list of sample data. + + :return: A tuple containing a batch dictionary and labels. + """""" + batch = {} + for k in samples[0][0].keys(): + if k == 'atom_feat': + v = pad_coords( + [torch.tensor(s[0][k]) for s in samples], + pad_idx=self.padding_idx, + dim=8, + ) + elif k == 'atom_mask': + v = pad_1d_tokens( + [torch.tensor(s[0][k]) for s in samples], pad_idx=self.padding_idx + ) + elif k == 'edge_feat': + v = pad_2d( + [torch.tensor(s[0][k]) for s in samples], + pad_idx=self.padding_idx, + dim=3, + ) + elif k == 'shortest_path': + v = pad_2d( + [torch.tensor(s[0][k]) for s in samples], pad_idx=self.padding_idx + ) + elif k == 'degree': + v = pad_1d_tokens( + [torch.tensor(s[0][k]) for s in samples], pad_idx=self.padding_idx + ) + elif k == 'pair_type': + v = pad_2d( + [torch.tensor(s[0][k]) for s in samples], + pad_idx=self.padding_idx, + dim=2, + ) + elif k == 'attn_bias': + v = pad_2d( + [torch.tensor(s[0][k]) for s in samples], pad_idx=self.padding_idx + ) + elif k == 'src_tokens': + v = pad_1d_tokens( + [torch.tensor(s[0][k]) for s in samples], pad_idx=self.padding_idx + ) + elif k == 'src_coord': + v = pad_coords( + [torch.tensor(s[0][k]) for s in samples], pad_idx=self.padding_idx + ) + batch[k] = v + try: + label = torch.tensor(np.array([s[1] for s in samples])) + except: + label = None + return batch, label + + +class LinearHead(nn.Module): + """"""Linear head."""""" + + def __init__( + self, + input_dim, + num_classes, + pooler_dropout, + ): + """""" + Initialize the Linear head. + + :param input_dim: Dimension of input features. + :param num_classes: Number of classes for output. + """""" + super().__init__() + self.out_proj = nn.Linear(input_dim, num_classes) + self.dropout = nn.Dropout(p=pooler_dropout) + + def forward(self, features, **kwargs): + """""" + Forward pass for the Linear head. + + :param features: Input features. + + :return: Output from the Linear head. + """""" + x = features + x = self.dropout(x) + x = self.out_proj(x) + return x + + +class ClassificationHead(nn.Module): + """"""Head for sentence-level classification tasks."""""" + + def __init__( + self, + input_dim, + inner_dim, + num_classes, + activation_fn, + pooler_dropout, + ): + """""" + Initialize the classification head. + + :param input_dim: Dimension of input features. + :param inner_dim: Dimension of the inner layer. + :param num_classes: Number of classes for classification. + :param activation_fn: Activation function name. + :param pooler_dropout: Dropout rate for the pooling layer. + """""" + super().__init__() + self.dense = nn.Linear(input_dim, inner_dim) + self.activation_fn = get_activation_fn(activation_fn) + self.dropout = nn.Dropout(p=pooler_dropout) + self.out_proj = nn.Linear(inner_dim, num_classes) + + def forward(self, features, **kwargs): + """""" + Forward pass for the classification head. + + :param features: Input features for classification. + + :return: Output from the classification head. + """""" + x = features + x = self.dropout(x) + x = self.dense(x) + x = self.activation_fn(x) + x = self.dropout(x) + x = self.out_proj(x) + return x + + +class NonLinearHead(nn.Module): + """""" + A neural network module used for simple classification tasks. It consists of a two-layered linear network + with a nonlinear activation function in between. + + Attributes: + - linear1: The first linear layer. + - linear2: The second linear layer that outputs to the desired dimensions. + - activation_fn: The nonlinear activation function. + """""" + + def __init__( + self, + input_dim, + out_dim, + activation_fn, + hidden=None, + ): + """""" + Initializes the NonLinearHead module. + + :param input_dim: Dimension of the input features. + :param out_dim: Dimension of the output. + :param activation_fn: The activation function to use. + :param hidden: Dimension of the hidden layer; defaults to the same as input_dim if not provided. + """""" + super().__init__() + hidden = input_dim if not hidden else hidden + self.linear1 = nn.Linear(input_dim, hidden) + self.linear2 = nn.Linear(hidden, out_dim) + self.activation_fn = get_activation_fn(activation_fn) + + def forward(self, x): + """""" + Forward pass of the NonLinearHead. + + :param x: Input tensor to the module. + + :return: Tensor after passing through the network. + """""" + x = self.linear1(x) + x = self.activation_fn(x) + x = self.linear2(x) + return x + + +@torch.jit.script +def gaussian(x, mean, std): + """""" + Gaussian function implemented for PyTorch tensors. + + :param x: The input tensor. + :param mean: The mean for the Gaussian function. + :param std: The standard deviation for the Gaussian function. + + :return: The output tensor after applying the Gaussian function. + """""" + pi = 3.14159 + a = (2 * pi) ** 0.5 + return torch.exp(-0.5 * (((x - mean) / std) ** 2)) / (a * std) + + +def get_activation_fn(activation): + """"""Returns the activation function corresponding to `activation`"""""" + + if activation == ""relu"": + return F.relu + elif activation == ""gelu"": + return F.gelu + elif activation == ""tanh"": + return torch.tanh + elif activation == ""linear"": + return lambda x: x + else: + raise RuntimeError(""--activation-fn {} not supported"".format(activation)) + + +class GaussianLayer(nn.Module): + """""" + A neural network module implementing a Gaussian layer, useful in graph neural networks. + + Attributes: + - K: Number of Gaussian kernels. + - means, stds: Embeddings for the means and standard deviations of the Gaussian kernels. + - mul, bias: Embeddings for scaling and bias parameters. + """""" + + def __init__(self, K=128, edge_types=1024): + """""" + Initializes the GaussianLayer module. + + :param K: Number of Gaussian kernels. + :param edge_types: Number of different edge types to consider. + + :return: An instance of the configured Gaussian kernel and edge types. + """""" + super().__init__() + self.K = K + self.means = nn.Embedding(1, K) + self.stds = nn.Embedding(1, K) + self.mul = nn.Embedding(edge_types, 1) + self.bias = nn.Embedding(edge_types, 1) + nn.init.uniform_(self.means.weight, 0, 3) + nn.init.uniform_(self.stds.weight, 0, 3) + nn.init.constant_(self.bias.weight, 0) + nn.init.constant_(self.mul.weight, 1) + + def forward(self, x, edge_type): + """""" + Forward pass of the GaussianLayer. + + :param x: Input tensor representing distances or other features. + :param edge_type: Tensor indicating types of edges in the graph. + + :return: Tensor transformed by the Gaussian layer. + """""" + mul = self.mul(edge_type).type_as(x) + bias = self.bias(edge_type).type_as(x) + x = mul * x.unsqueeze(-1) + bias + x = x.expand(-1, -1, -1, self.K) + mean = self.means.weight.float().view(-1) + std = self.stds.weight.float().view(-1).abs() + 1e-5 + return gaussian(x.float(), mean, std).type_as(self.means.weight) + + +class NumericalEmbed(nn.Module): + """""" + Numerical embedding module, typically used for embedding edge features in graph neural networks. + + Attributes: + - K: Output dimension for embeddings. + - mul, bias, w_edge: Embeddings for transformation parameters. + - proj: Projection layer to transform inputs. + - ln: Layer normalization. + """""" + + def __init__(self, K=128, edge_types=1024, activation_fn='gelu'): + """""" + Initializes the NonLinearHead. + + :param input_dim: The input dimension of the first layer. + :param out_dim: The output dimension of the second layer. + :param activation_fn: The activation function to use. + :param hidden: The dimension of the hidden layer; defaults to input_dim if not specified. + """""" + super().__init__() + self.K = K + self.mul = nn.Embedding(edge_types, 1) + self.bias = nn.Embedding(edge_types, 1) + self.w_edge = nn.Embedding(edge_types, K) + + self.proj = NonLinearHead(1, K, activation_fn, hidden=2 * K) + self.ln = nn.LayerNorm(K) + + nn.init.constant_(self.bias.weight, 0) + nn.init.constant_(self.mul.weight, 1) + nn.init.kaiming_normal_(self.w_edge.weight) + + def forward(self, x, edge_type): # edge_type, atoms + """""" + Forward pass of the NonLinearHead. + + :param x: Input tensor to the classification head. + + :return: The output tensor after passing through the layers. + """""" + mul = self.mul(edge_type).type_as(x) + bias = self.bias(edge_type).type_as(x) + w_edge = self.w_edge(edge_type).type_as(x) + edge_emb = w_edge * torch.sigmoid(mul * x.unsqueeze(-1) + bias) + + edge_proj = x.unsqueeze(-1).type_as(self.mul.weight) + edge_proj = self.proj(edge_proj) + edge_proj = self.ln(edge_proj) + + h = edge_proj + edge_emb + h = h.type_as(self.mul.weight) + return h + + +def molecule_architecture(model_size='84m'): + args = Dict() + if model_size == '84m': + args.num_encoder_layers = 12 + args.encoder_embed_dim = 768 + args.num_attention_heads = 48 + args.ffn_embedding_dim = 768 + args.encoder_attention_heads = 48 + elif model_size == '164m': + args.num_encoder_layers = 24 + args.encoder_embed_dim = 768 + args.num_attention_heads = 48 + args.ffn_embedding_dim = 768 + args.encoder_attention_heads = 48 + elif model_size == '310m': + args.num_encoder_layers = 32 + args.encoder_embed_dim = 1024 + args.num_attention_heads = 64 + args.ffn_embedding_dim = 1024 + args.encoder_attention_heads = 64 + elif model_size == '570m': + args.num_encoder_layers = 32 + args.encoder_embed_dim = 1536 + args.num_attention_heads = 96 + args.ffn_embedding_dim = 1536 + args.encoder_attention_heads = 96 + elif model_size == '1.1B': + args.num_encoder_layers = 64 + args.encoder_embed_dim = 1536 + args.num_attention_heads = 96 + args.ffn_embedding_dim = 1536 + args.encoder_attention_heads = 96 + else: + raise ValueError('Current not support data type: {}'.format(model_size)) + args.pair_embed_dim = 512 + args.pair_hidden_dim = 64 + args.dropout = 0.1 + args.attention_dropout = 0.1 + args.activation_dropout = 0.0 + args.activation_fn = ""gelu"" + args.droppath_prob = 0.0 + args.pair_dropout = 0.25 + args.backbone = ""transformer"" + args.gaussian_std_width = 1.0 + args.gaussian_mean_start = 0.0 + args.gaussian_mean_stop = 9.0 + args.pooler_dropout = 0.0 + args.pooler_activation_fn = ""tanh"" + return args +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/models/transformersv2.py",".py","23760","770","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + + +def softmax_dropout( + input, dropout_prob, is_training=True, mask=None, bias=None, inplace=True +): + """"""softmax dropout, and mask, bias are optional. + Args: + input (torch.Tensor): input tensor + dropout_prob (float): dropout probability + is_training (bool, optional): is in training or not. Defaults to True. + mask (torch.Tensor, optional): the mask tensor, use as input + mask . Defaults to None. + bias (torch.Tensor, optional): the bias tensor, use as input + bias . Defaults to None. + + Returns: + torch.Tensor: the result after softmax + """""" + input = input.contiguous() + if not inplace: + # copy a input for non-inplace case + input = input.clone() + if mask is not None: + input += mask + if bias is not None: + input += bias + return F.dropout(F.softmax(input, dim=-1), p=dropout_prob, training=is_training) + + +def permute_final_dims(tensor: torch.Tensor, inds): + zero_index = -1 * len(inds) + first_inds = list(range(len(tensor.shape[:zero_index]))) + return tensor.permute(first_inds + [zero_index + i for i in inds]) + + +class Dropout(nn.Module): + def __init__(self, p): + super().__init__() + self.p = p + + def forward(self, x, inplace: bool = False): + if self.p > 0 and self.training: + return F.dropout(x, p=self.p, training=True, inplace=inplace) + else: + return x + + +class Linear(nn.Linear): + def __init__( + self, + d_in: int, + d_out: int, + bias: bool = True, + init: str = ""default"", + ): + super(Linear, self).__init__(d_in, d_out, bias=bias) + + self.use_bias = bias + + if self.use_bias: + with torch.no_grad(): + self.bias.fill_(0) + + if init == ""default"": + self._trunc_normal_init(1.0) + elif init == ""relu"": + self._trunc_normal_init(2.0) + elif init == ""glorot"": + self._glorot_uniform_init() + elif init == ""gating"": + self._zero_init(self.use_bias) + elif init == ""normal"": + self._normal_init() + elif init == ""final"": + self._zero_init(False) + else: + raise ValueError(""Invalid init method."") + + def _trunc_normal_init(self, scale=1.0): + # Constant from scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.) + TRUNCATED_NORMAL_STDDEV_FACTOR = 0.87962566103423978 + _, fan_in = self.weight.shape + scale = scale / max(1, fan_in) + std = (scale**0.5) / TRUNCATED_NORMAL_STDDEV_FACTOR + nn.init.trunc_normal_(self.weight, mean=0.0, std=std) + + def _glorot_uniform_init(self): + nn.init.xavier_uniform_(self.weight, gain=1) + + def _zero_init(self, use_bias=True): + with torch.no_grad(): + self.weight.fill_(0.0) + if use_bias: + with torch.no_grad(): + self.bias.fill_(1.0) + + def _normal_init(self): + torch.nn.init.kaiming_normal_(self.weight, nonlinearity=""linear"") + + +class Embedding(nn.Embedding): + def __init__( + self, + num_embeddings: int, + embedding_dim: int, + padding_idx: int = None, + ): + super(Embedding, self).__init__( + num_embeddings, embedding_dim, padding_idx=padding_idx + ) + self._normal_init() + + if padding_idx is not None: + self.weight.data[self.padding_idx].zero_() + + def _normal_init(self, std=0.02): + nn.init.normal_(self.weight, mean=0.0, std=std) + + +class Transition(nn.Module): + def __init__(self, d_in, n, dropout=0.0): + + super(Transition, self).__init__() + + self.d_in = d_in + self.n = n + + self.linear_1 = Linear(self.d_in, self.n * self.d_in, init=""relu"") + self.act = nn.GELU() + self.linear_2 = Linear(self.n * self.d_in, d_in, init=""final"") + self.dropout = dropout + + def _transition(self, x): + x = self.linear_1(x) + x = self.act(x) + x = F.dropout(x, p=self.dropout, training=self.training) + x = self.linear_2(x) + return x + + def forward( + self, + x: torch.Tensor, + ) -> torch.Tensor: + + x = self._transition(x=x) + return x + + +class Attention(nn.Module): + def __init__( + self, + q_dim: int, + k_dim: int, + v_dim: int, + pair_dim: int, + head_dim: int, + num_heads: int, + gating: bool = False, + dropout: float = 0.0, + ): + super(Attention, self).__init__() + + self.num_heads = num_heads + total_dim = head_dim * self.num_heads + self.gating = gating + self.linear_q = Linear(q_dim, total_dim, bias=False, init=""glorot"") + self.linear_k = Linear(k_dim, total_dim, bias=False, init=""glorot"") + self.linear_v = Linear(v_dim, total_dim, bias=False, init=""glorot"") + self.linear_o = Linear(total_dim, q_dim, init=""final"") + self.linear_g = None + if self.gating: + self.linear_g = Linear(q_dim, total_dim, init=""gating"") + # precompute the 1/sqrt(head_dim) + self.norm = head_dim**-0.5 + self.dropout = dropout + self.linear_bias = Linear(pair_dim, num_heads) + + def forward( + self, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + pair: torch.Tensor, + mask: torch.Tensor = None, + ) -> torch.Tensor: + g = None + if self.linear_g is not None: + # gating, use raw query input + g = self.linear_g(q) + + q = self.linear_q(q) + q *= self.norm + k = self.linear_k(k) + v = self.linear_v(v) + + q = q.view(q.shape[:-1] + (self.num_heads, -1)).transpose(-2, -3).contiguous() + k = k.view(k.shape[:-1] + (self.num_heads, -1)).transpose(-2, -3).contiguous() + v = v.view(v.shape[:-1] + (self.num_heads, -1)).transpose(-2, -3) + + attn = torch.matmul(q, k.transpose(-1, -2)) + del q, k + bias = self.linear_bias(pair).permute(0, 3, 1, 2).contiguous() + attn = softmax_dropout(attn, self.dropout, self.training, mask=mask, bias=bias) + o = torch.matmul(attn, v) + del attn, v + + o = o.transpose(-2, -3).contiguous() + o = o.view(*o.shape[:-2], -1) + + if g is not None: + o = torch.sigmoid(g) * o + + # merge heads + o = self.linear_o(o) + return o + + +class OuterProduct(nn.Module): + def __init__(self, d_atom, d_pair, d_hid=32): + super(OuterProduct, self).__init__() + + self.d_atom = d_atom + self.d_pair = d_pair + self.d_hid = d_hid + + self.linear_in = nn.Linear(d_atom, d_hid * 2) + self.linear_out = nn.Linear(d_hid**2, d_pair) + self.act = nn.GELU() + self._memory_efficient = True + + def _opm(self, a, b): + bsz, n, d = a.shape + # outer = torch.einsum(""...bc,...de->...bdce"", a, b) + a = a.view(bsz, n, 1, d, 1) + b = b.view(bsz, 1, n, 1, d) + outer = a * b + outer = outer.view(outer.shape[:-2] + (-1,)) + outer = self.linear_out(outer) + return outer + + def forward( + self, + m: torch.Tensor, + op_mask: Optional[torch.Tensor] = None, + op_norm: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + + ab = self.linear_in(m) + ab = ab * op_mask + a, b = ab.chunk(2, dim=-1) + + if self._memory_efficient and torch.is_grad_enabled(): + z = checkpoint(self._opm, a, b, use_reentrant=False) + else: + z = self._opm(a, b) + + z *= op_norm + return z + + +class AtomFeature(nn.Module): + """""" + Compute atom features for each atom in the molecule. + """""" + + def __init__( + self, + num_atom, + num_degree, + hidden_dim, + ): + super(AtomFeature, self).__init__() + self.atom_encoder = Embedding(num_atom, hidden_dim, padding_idx=0) + self.degree_encoder = Embedding(num_degree, hidden_dim, padding_idx=0) + self.vnode_encoder = Embedding(1, hidden_dim) + + def forward(self, batched_data, token_feat): + x, degree = ( + batched_data[""atom_feat""], + batched_data[""degree""], + ) + n_graph, n_node = x.size()[:2] + + node_feature = self.atom_encoder(x).sum(dim=-2) # [n_graph, n_node, n_hidden] + dtype = node_feature.dtype + degree_feature = self.degree_encoder(degree) + node_feature = node_feature + degree_feature + token_feat + + graph_token_feature = self.vnode_encoder.weight.unsqueeze(0).repeat( + n_graph, 1, 1 + ) + + graph_node_feature = torch.cat([graph_token_feature, node_feature], dim=1) + return graph_node_feature.type(dtype) + + +class EdgeFeature(nn.Module): + """""" + Compute attention bias for each head. + """""" + + def __init__( + self, + pair_dim, + num_edge, + num_spatial, + ): + super(EdgeFeature, self).__init__() + self.pair_dim = pair_dim + + self.edge_encoder = Embedding(num_edge, pair_dim, padding_idx=0) + self.shorest_path_encoder = Embedding(num_spatial, pair_dim, padding_idx=0) + self.vnode_virtual_distance = Embedding(1, pair_dim) + + def forward(self, batched_data, graph_attn_bias): + shortest_path = batched_data[""shortest_path""] + edge_input = batched_data[""edge_feat""] + + graph_attn_bias[:, 1:, 1:, :] = self.shorest_path_encoder(shortest_path) + + # reset spatial pos here + t = self.vnode_virtual_distance.weight.view(1, 1, self.pair_dim) + graph_attn_bias[:, 1:, 0, :] = t + graph_attn_bias[:, 0, :, :] = t + + edge_input = self.edge_encoder(edge_input).mean(-2) + graph_attn_bias[:, 1:, 1:, :] = graph_attn_bias[:, 1:, 1:, :] + edge_input + return graph_attn_bias + + +class SE3InvariantKernel(nn.Module): + """""" + Compute 3D attention bias according to the position information for each head. + """""" + + def __init__( + self, + pair_dim, + num_pair, + num_kernel, + std_width=1.0, + start=0.0, + stop=9.0, + ): + super(SE3InvariantKernel, self).__init__() + self.num_kernel = num_kernel + + self.gaussian = GaussianKernel( + self.num_kernel, + num_pair, + std_width=std_width, + start=start, + stop=stop, + ) + self.out_proj = NonLinear(self.num_kernel, pair_dim) + + def forward(self, dist, node_type_edge): + edge_feature = self.gaussian( + dist, + node_type_edge.long(), + ) + edge_feature = self.out_proj(edge_feature) + + return edge_feature + + +@torch.jit.script +def gaussian(x, mean, std): + pi = 3.14159 + a = (2 * pi) ** 0.5 + return torch.exp(-0.5 * (((x - mean) / std) ** 2)) / (a * std) + + +class GaussianKernel(nn.Module): + def __init__(self, K=128, num_pair=512, std_width=1.0, start=0.0, stop=9.0): + super().__init__() + self.K = K + std_width = std_width + start = start + stop = stop + mean = torch.linspace(start, stop, K) + self.std = std_width * (mean[1] - mean[0]) + self.register_buffer(""mean"", mean) + self.mul = Embedding(num_pair, 1, padding_idx=0) + self.bias = Embedding(num_pair, 1, padding_idx=0) + nn.init.constant_(self.bias.weight, 0) + nn.init.constant_(self.mul.weight, 1.0) + + def forward(self, x, atom_pair): + mul = self.mul(atom_pair).abs().sum(dim=-2) + bias = self.bias(atom_pair).sum(dim=-2) + x = mul * x.unsqueeze(-1) + bias + x = x.expand(-1, -1, -1, self.K) + mean = self.mean.float().view(-1) + return gaussian(x.float(), mean, self.std) + + +class NonLinear(nn.Module): + def __init__(self, input, output_size, hidden=None): + super(NonLinear, self).__init__() + + if hidden is None: + hidden = input + self.layer1 = Linear(input, hidden, init=""relu"") + self.layer2 = Linear(hidden, output_size, init=""final"") + + def forward(self, x): + x = self.layer1(x) + x = F.gelu(x) + x = self.layer2(x) + return x + + def zero_init(self): + nn.init.zeros_(self.layer2.weight) + nn.init.zeros_(self.layer2.bias) + + +class MovementPredictionHead(nn.Module): + def __init__( + self, + embed_dim: int, + pair_dim: int, + num_head: int, + ): + super().__init__() + self.layer_norm = nn.LayerNorm(embed_dim) + self.embed_dim = embed_dim + self.q_proj = Linear(embed_dim, embed_dim, bias=False, init=""glorot"") + self.k_proj = Linear(embed_dim, embed_dim, bias=False, init=""glorot"") + self.v_proj = Linear(embed_dim, embed_dim, bias=False, init=""glorot"") + self.num_head = num_head + self.scaling = (embed_dim // num_head) ** -0.5 + self.force_proj1 = Linear(embed_dim, 1, init=""final"", bias=False) + self.linear_bias = Linear(pair_dim, num_head) + self.pair_layer_norm = nn.LayerNorm(pair_dim) + self.dropout = 0.1 + + def zero_init(self): + nn.init.zeros_(self.force_proj1.weight) + + def forward( + self, + query, + pair, + attn_mask, + delta_pos, + ) -> None: + bsz, n_node, _ = query.size() + query = self.layer_norm(query) + q = ( + self.q_proj(query).view(bsz, n_node, self.num_head, -1).transpose(1, 2) + * self.scaling + ) + k = self.k_proj(query).view(bsz, n_node, self.num_head, -1).transpose(1, 2) + v = self.v_proj(query).view(bsz, n_node, self.num_head, -1).transpose(1, 2) + attn = q @ k.transpose(-1, -2) # [bsz, head, n, n] + + pair = self.pair_layer_norm(pair) + bias = self.linear_bias(pair).permute(0, 3, 1, 2).contiguous() + attn_probs = softmax_dropout( + attn, + self.dropout, + self.training, + mask=attn_mask.contiguous(), + bias=bias.contiguous(), + ).view(bsz, self.num_head, n_node, n_node) + rot_attn_probs = attn_probs.unsqueeze(-1) * delta_pos.unsqueeze(1).type_as( + attn_probs + ) # [bsz, head, n, n, 3] + rot_attn_probs = rot_attn_probs.permute(0, 1, 4, 2, 3) + x = rot_attn_probs @ v.unsqueeze(2) # [bsz, head , 3, n, d] + x = x.permute(0, 3, 2, 1, 4).contiguous().view(bsz, n_node, 3, -1) + cur_force = self.force_proj1(x).view(bsz, n_node, 3) + return cur_force + + +class DropPath(torch.nn.Module): + """"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""""" + + def __init__(self, prob=None): + super(DropPath, self).__init__() + self.drop_prob = prob + + def forward(self, x): + if self.drop_prob == 0.0 or not self.training: + return x + keep_prob = 1 - self.drop_prob + shape = (x.shape[0],) + (1,) * ( + x.ndim - 1 + ) # work with diff dim tensors, not just 2D ConvNets + random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) + random_tensor.floor_() # binarize + output = x.div(keep_prob) * random_tensor + return output + + def extra_repr(self) -> str: + return f""prob={self.drop_prob}"" + + +class TriangleMultiplication(nn.Module): + def __init__(self, d_pair, d_hid): + super(TriangleMultiplication, self).__init__() + + self.linear_ab_p = Linear(d_pair, d_hid * 2) + self.linear_ab_g = Linear(d_pair, d_hid * 2, init=""gating"") + + self.linear_g = Linear(d_pair, d_pair, init=""gating"") + self.linear_z = Linear(d_hid, d_pair, init=""final"") + + self.layer_norm_out = nn.LayerNorm(d_hid) + + def forward( + self, + z: torch.Tensor, + mask: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + + mask = mask.unsqueeze(-1) + mask = mask * (mask.shape[-2] ** -0.5) + + g = self.linear_g(z) + if self.training: + ab = self.linear_ab_p(z) * mask * torch.sigmoid(self.linear_ab_g(z)) + else: + ab = self.linear_ab_p(z) + ab *= mask + ab *= torch.sigmoid(self.linear_ab_g(z)) + a, b = torch.chunk(ab, 2, dim=-1) + del z, ab + + a1 = permute_final_dims(a, (2, 0, 1)) + b1 = b.transpose(-1, -3) + x = torch.matmul(a1, b1) + del a1, b1 + b2 = permute_final_dims(b, (2, 0, 1)) + a2 = a.transpose(-1, -3) + x = x + torch.matmul(a2, b2) + del a, b, a2, b2 + + x = permute_final_dims(x, (1, 2, 0)) + + x = self.layer_norm_out(x) + x = self.linear_z(x) + return g * x + + +def get_activation_fn(activation): + """"""Returns the activation function corresponding to `activation`"""""" + + if activation == ""relu"": + return F.relu + elif activation == ""gelu"": + return F.gelu + elif activation == ""tanh"": + return torch.tanh + elif activation == ""linear"": + return lambda x: x + else: + raise RuntimeError(""--activation-fn {} not supported"".format(activation)) + + +class TransformerEncoderLayerV2(nn.Module): + """""" + Implements a Transformer-M Encoder Layer. + """""" + + def __init__( + self, + embedding_dim: int = 768, + pair_dim: int = 64, + pair_hidden_dim: int = 32, + ffn_embedding_dim: int = 3072, + num_attention_heads: int = 8, + dropout: float = 0.1, + attention_dropout: float = 0.1, + activation_dropout: float = 0.1, + activation_fn: str = ""relu"", + droppath_prob: float = 0.0, + pair_dropout: float = 0.25, + ) -> None: + super().__init__() + + # Initialize parameters + self.embedding_dim = embedding_dim + self.num_attention_heads = num_attention_heads + self.attention_dropout = attention_dropout + + if droppath_prob > 0.0: + self.dropout_module = DropPath(droppath_prob) + else: + self.dropout_module = Dropout(dropout) + + # Initialize blocks + self.activation_fn = get_activation_fn(activation_fn) + head_dim = self.embedding_dim // self.num_attention_heads + self.self_attn = Attention( + self.embedding_dim, + self.embedding_dim, + self.embedding_dim, + pair_dim=pair_dim, + head_dim=head_dim, + num_heads=self.num_attention_heads, + gating=False, + dropout=attention_dropout, + ) + + # layer norm associated with the self attention layer + self.self_attn_layer_norm = nn.LayerNorm(self.embedding_dim) + + self.ffn = Transition( + self.embedding_dim, + ffn_embedding_dim // self.embedding_dim, + dropout=activation_dropout, + ) + + # layer norm associated with the position wise feed-forward NN + self.final_layer_norm = nn.LayerNorm(self.embedding_dim) + self.x_layer_norm_opm = nn.LayerNorm(self.embedding_dim) + + self.opm = OuterProduct(self.embedding_dim, pair_dim, d_hid=pair_hidden_dim) + # self.pair_layer_norm_opm = nn.LayerNorm(pair_dim) + + self.pair_layer_norm_ffn = nn.LayerNorm(pair_dim) + self.pair_ffn = Transition( + pair_dim, + 1, + dropout=activation_dropout, + ) + + self.pair_dropout = pair_dropout + self.pair_layer_norm_trimul = nn.LayerNorm(pair_dim) + self.pair_tri_mul = TriangleMultiplication(pair_dim, pair_hidden_dim) + + def shared_dropout(self, x, shared_dim, dropout): + shape = list(x.shape) + shape[shared_dim] = 1 + with torch.no_grad(): + mask = x.new_ones(shape) + return F.dropout(mask, p=dropout, training=self.training) * x + + def forward( + self, + x: torch.Tensor, + pair: torch.Tensor, + pair_mask: torch.Tensor, + self_attn_mask: Optional[torch.Tensor] = None, + op_mask: Optional[torch.Tensor] = None, + op_norm: Optional[torch.Tensor] = None, + ): + """""" + LayerNorm is applied either before or after the self-attention/ffn + modules similar to the original Transformer implementation. + """""" + residual = x + x = self.self_attn_layer_norm(x) + x = self.self_attn( + x, + x, + x, + pair=pair, + mask=self_attn_mask, + ) + x = self.dropout_module(x) + x = residual + x + + x = x + self.dropout_module(self.ffn(self.final_layer_norm(x))) + + pair = pair + self.dropout_module( + self.opm(self.x_layer_norm_opm(x), op_mask, op_norm) + ) + + # trimul + pair = pair + self.shared_dropout( + self.pair_tri_mul(self.pair_layer_norm_trimul(pair), pair_mask), + -3, + self.pair_dropout, + ) + + # ffn + pair = pair + self.dropout_module(self.pair_ffn(self.pair_layer_norm_ffn(pair))) + + return x, pair + + +class TransformerEncoderWithPairV2(nn.Module): + def __init__( + self, + num_encoder_layers: int = 6, + embedding_dim: int = 768, + pair_dim: int = 64, + pair_hidden_dim: int = 32, + ffn_embedding_dim: int = 3072, + num_attention_heads: int = 8, + dropout: float = 0.1, + attention_dropout: float = 0.1, + activation_dropout: float = 0.0, + activation_fn: str = ""gelu"", + droppath_prob: float = 0.0, + pair_dropout: float = 0.25, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.num_head = num_attention_heads + self.layer_norm = nn.LayerNorm(embedding_dim) + self.pair_layer_norm = nn.LayerNorm(pair_dim) + self.layers = nn.ModuleList([]) + + if droppath_prob > 0: + droppath_probs = [ + x.item() for x in torch.linspace(0, droppath_prob, num_encoder_layers) + ] + else: + droppath_probs = None + + self.layers.extend( + [ + TransformerEncoderLayerV2( + embedding_dim=embedding_dim, + pair_dim=pair_dim, + pair_hidden_dim=pair_hidden_dim, + ffn_embedding_dim=ffn_embedding_dim, + num_attention_heads=num_attention_heads, + dropout=dropout, + attention_dropout=attention_dropout, + activation_dropout=activation_dropout, + activation_fn=activation_fn, + droppath_prob=( + droppath_probs[i] if droppath_probs is not None else 0 + ), + pair_dropout=pair_dropout, + ) + for i in range(num_encoder_layers) + ] + ) + + def forward( + self, + x, + pair, + atom_mask, + pair_mask, + attn_mask=None, + ) -> None: + + x = self.layer_norm(x) + pair = self.pair_layer_norm(pair) + op_mask = atom_mask.unsqueeze(-1) + op_mask = op_mask * (op_mask.size(-2) ** -0.5) + eps = 1e-3 + op_norm = 1.0 / (eps + torch.einsum(""...bc,...dc->...bdc"", op_mask, op_mask)) + for layer in self.layers: + x, pair = layer( + x, + pair, + pair_mask=pair_mask, + self_attn_mask=attn_mask, + op_mask=op_mask, + op_norm=op_norm, + ) + return x, pair +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/pretrain/trainer.py",".py","21100","498","import logging +import os +import math +import random +from pathlib import Path + +import numpy as np +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.optim as optim +from torch.nn.utils import clip_grad_norm_ +from hydra.core.hydra_config import HydraConfig +from hydra.utils import get_original_cwd +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader +from torch.utils.tensorboard import SummaryWriter +from unimol_tools.tasks.trainer import get_linear_schedule_with_warmup +from unimol_tools.utils.dynamic_loss_scaler import DynamicLossScaler + +logger = logging.getLogger(__name__) + + +class UniMolPretrainTrainer: + def __init__(self, model, dataset, loss_fn, config, local_rank=None, resume: str=None, valid_dataset=None): + self.model = model + self.dataset = dataset + self.valid_dataset = valid_dataset + self.loss_fn = loss_fn + self.config = config + # Use ranks provided by torchrun + self.local_rank = int(os.environ.get(""LOCAL_RANK"", 0)) if local_rank is None else local_rank + self.rank = int(os.environ.get(""RANK"", 0)) + self.fp16 = getattr(config, ""fp16"", True) + + run_dir = getattr(config, ""output_dir"", None) + if run_dir: + if not os.path.isabs(run_dir): + run_dir = os.path.join(get_original_cwd(), run_dir) + else: + run_dir = HydraConfig.get().run.dir + self.ckpt_dir = Path(os.path.join(run_dir, 'checkpoints')) + + # DDP setup + if 'WORLD_SIZE' in os.environ and int(os.environ['WORLD_SIZE']) > 1: + torch.cuda.set_device(self.local_rank) + dist.init_process_group(backend='nccl') + self.rank = dist.get_rank() + self.model = self.model.to(self.local_rank) + if self.fp16: + self.model = self.model.half() + if isinstance(self.loss_fn, nn.Module): + self.loss_fn = self.loss_fn.to(self.local_rank).half() + else: + if isinstance(self.loss_fn, nn.Module): + self.loss_fn = self.loss_fn.to(self.local_rank) + self.model = DDP(self.model, device_ids=[self.local_rank]) + else: + self.model = self.model.cuda() + if self.fp16: + self.model = self.model.half() + if isinstance(self.loss_fn, nn.Module): + self.loss_fn = self.loss_fn.cuda().half() + else: + if isinstance(self.loss_fn, nn.Module): + self.loss_fn = self.loss_fn.cuda() + + self.writer = SummaryWriter(log_dir=run_dir) if self.rank == 0 else None + if self.rank == 0: + os.makedirs(self.ckpt_dir, exist_ok=True) + logger.info(f""Checkpoints will be saved to {self.ckpt_dir}"") + + decay, no_decay = [], [] + for name, p in self.model.named_parameters(): + if not p.requires_grad: + continue + if p.ndim == 1 or name.endswith("".bias""): + no_decay.append(p) + else: + decay.append(p) + optim_groups = [ + {""params"": decay, ""weight_decay"": self.config.weight_decay}, + {""params"": no_decay, ""weight_decay"": 0.0}, + ] + + self.optimizer = optim.AdamW( + optim_groups, + lr=self.config.lr, + betas=getattr(self.config, ""adam_betas"", (0.9, 0.99)), + eps=getattr(self.config, ""adam_eps"", 1e-6), + ) + self.scheduler = None + warmup_steps = getattr(config, ""warmup_steps"", 0) + total_steps = getattr(config, ""total_steps"", 0) + if warmup_steps > 0 and total_steps > 0: + self.scheduler = get_linear_schedule_with_warmup( + self.optimizer, warmup_steps, total_steps + ) + self.criterion = nn.CrossEntropyLoss() + + self.best_loss = float(""inf"") + self.patience = getattr(config, ""patience"", -1) + self.no_improve_steps = 0 + + # DDP DataLoader + if 'WORLD_SIZE' in os.environ and int(os.environ['WORLD_SIZE']) > 1: + self.sampler = torch.utils.data.distributed.DistributedSampler(self.dataset) + self.valid_sampler = ( + torch.utils.data.distributed.DistributedSampler(self.valid_dataset, shuffle=False) + if self.valid_dataset is not None + else None + ) + else: + self.sampler = None + self.valid_sampler = None + logger.info(f""Using sampler: {self.sampler}"") + + g = torch.Generator() + g.manual_seed(config.seed) + + num_workers = getattr(self.config, ""num_workers"", 8) + collate_fn = ( + self.model.module.batch_collate_fn + if isinstance(self.model, DDP) + else self.model.batch_collate_fn + ) + + self.dataloader = DataLoader( + self.dataset, + batch_size=self.config.batch_size, + shuffle=(self.sampler is None), + sampler=self.sampler, + num_workers=num_workers, + pin_memory=True, + collate_fn=collate_fn, + worker_init_fn=seed_worker, + generator=g, + ) + if self.valid_dataset is not None: + self.valid_dataloader = DataLoader( + self.valid_dataset, + batch_size=self.config.batch_size, + shuffle=False, + sampler=self.valid_sampler, + num_workers=num_workers, + pin_memory=True, + collate_fn=collate_fn, + ) + else: + self.valid_dataloader = None + + self.world_size = ( + dist.get_world_size() if dist.is_available() and dist.is_initialized() else 1 + ) + if self.rank == 0: + effective_bs = ( + self.config.batch_size * self.config.update_freq * self.world_size + ) + logger.info( + f""GPUs: {self.world_size}, batch size per GPU: {self.config.batch_size}, update_freq: {self.config.update_freq}, total batch size: {effective_bs}"" + ) + logger.info(f""Learning rate: {self.config.lr:.4e}"") + + if self.fp16 and not torch.cuda.is_available(): + logger.warning(""FP16 requested but CUDA is not available; disabling fp16."") + self.fp16 = False + self.scaler = ( + DynamicLossScaler( + init_scale=getattr(config, ""fp16_init_scale"", 4), + scale_window=getattr(config, ""fp16_scale_window"", 256), + ) + if self.fp16 + else None + ) + + # resume training from a checkpoint if provided or detect last + self.start_epoch = 0 + self.global_step = 0 + resume_path = resume + if resume_path is not None and not os.path.isabs(resume_path): + resume_path = os.path.join(run_dir, resume_path) + if resume_path is None: + last_ckpt = self.ckpt_dir / 'checkpoint_last.ckpt' + if last_ckpt.exists(): + resume_path = str(last_ckpt) + if resume_path is not None and os.path.isfile(resume_path): + self._load_checkpoint(resume_path) + logger.info(f""Resumed from checkpoint: {resume_path}"") + else: + logger.info(""No checkpoint found, starting from scratch."") + + def train(self, epochs=None, max_steps=None): + epochs = self.config.epochs if epochs is None else epochs + max_steps = max_steps or getattr(self.config, ""total_steps"", 0) + if epochs <= 0: + epochs = math.inf + log_every = getattr(self.config, ""log_every_n_steps"", 100) + save_every = getattr(self.config, ""save_every_n_steps"", 1000) + + epoch = self.start_epoch + stop_training = False + while epoch < epochs and not stop_training: + display_epoch = epoch + 1 + if self.sampler: + self.sampler.set_epoch(epoch) + if hasattr(self.dataset, ""set_epoch""): + self.dataset.set_epoch(epoch) + self.model.train() + logger.info(f""Starting epoch {display_epoch}"") + logger.info(""Start iterating over samples"") + step_logging_infos = [] + epoch_logging_infos = [] + num_batches = len(self.dataloader) + update_freq = getattr(self.config, ""update_freq"", 1) + self.optimizer.zero_grad() + accum_logging = [] + + for i, batch in enumerate(self.dataloader, start=1): + net_input, net_target = self.decorate_batch(batch) + loss, sample_size, logging_info = self.loss_fn( + self.model, net_input, net_target + ) + if self.fp16: + self.scaler.scale(loss / sample_size / update_freq).backward() + else: + (loss / sample_size / update_freq).backward() + accum_logging.append(logging_info) + + if i % update_freq == 0 or i == num_batches: + grad_norm = 0.0 + if self.fp16: + self.scaler.unscale_(self.model.parameters()) + + clip_val = getattr(self.config, ""clip_grad_norm"", 0) + if clip_val and clip_val > 0: + grad_norm = clip_grad_norm_(self.model.parameters(), clip_val) + else: + for p in self.model.parameters(): + if p.grad is not None: + grad_norm += p.grad.data.float().norm(2).item() ** 2 + grad_norm = grad_norm ** 0.5 + + overflow = False + if self.fp16: + try: + self.scaler.check_overflow(grad_norm) + except OverflowError: + overflow = True + + if overflow: + self.optimizer.zero_grad() + if self.rank == 0: + logger.warning( + f""gradient overflow detected, ignoring gradient, setting loss scale to: {self.scaler.loss_scale:.1f}"" + ) + accum_logging = [] + continue + self.optimizer.step() + if self.fp16: + self.scaler.update() + if self.scheduler is not None: + self.scheduler.step() + self.optimizer.zero_grad() + + merged_log = {} + for log in accum_logging: + for k, v in log.items(): + merged_log[k] = merged_log.get(k, 0) + v + step_logging_infos.append(merged_log) + epoch_logging_infos.append(merged_log) + self.global_step += 1 + + if self.writer: + step_metrics = self.loss_fn.reduce_metrics([merged_log]) + self.writer.add_scalar('Step/loss', step_metrics.get('loss', 0), self.global_step) + for key, value in step_metrics.items(): + if key == 'loss': + continue + self.writer.add_scalar(f'Step/{key}', value, self.global_step) + accum_logging = [] + + if log_every > 0 and self.global_step % log_every == 0 and self.rank == 0: + self.reduce_metrics( + step_logging_infos, + writer=self.writer, + logger=logger, + step=self.global_step, + split=""train_inner"", + unit=""Step"", + epoch=display_epoch, + inner_step=i, + inner_total=num_batches, + ) + step_logging_infos = [] + + if save_every > 0 and self.global_step % save_every == 0: + val_metrics = None + if self.valid_dataloader is not None: + val_metrics = self.evaluate(self.global_step, log=self.rank == 0) + if self.rank == 0: + self._save_checkpoint(epoch, self.global_step, 'checkpoint_last.ckpt') + if self.valid_dataloader is not None and val_metrics is not None: + curr_loss = val_metrics.get('loss', float('inf')) + if curr_loss < self.best_loss: + self.best_loss = curr_loss + self.no_improve_steps = 0 + logger.info( + f""New best model at step {self.global_step} with loss {curr_loss:.4f}"" + ) + self._save_checkpoint(epoch, self.global_step, 'checkpoint_best.ckpt') + else: + self.no_improve_steps += 1 + if ( + self.patience >= 0 + and self.no_improve_steps > self.patience + ): + logger.info( + f""Early stopping triggered at step {self.global_step}"" + ) + stop_training = True + self._save_checkpoint(epoch, self.global_step) + if stop_training: + break + + if max_steps and self.global_step >= max_steps: + if self.rank == 0: + logger.info( + f""Reached max steps {max_steps}, stopping training"" + ) + stop_training = True + break + + if self.rank == 0: + logger.info( + f""End of epoch {display_epoch} (average epoch stats below)"" + ) + self.reduce_metrics( + epoch_logging_infos, + writer=self.writer, + logger=logger, + step=display_epoch, + split=""train"", + unit=""Epoch"", + ) + epoch += 1 + + final_epoch = epoch - 1 + if self.rank == 0: + self._save_checkpoint(final_epoch, self.global_step, 'checkpoint_last.ckpt') + + if self.writer: + self.writer.close() + + def _save_checkpoint(self, epoch, step, name=None): + if self.rank != 0: + return + ckpt = { + ""model"": self.model.module.state_dict() + if isinstance(self.model, torch.nn.parallel.DistributedDataParallel) + else self.model.state_dict(), + ""optimizer"": self.optimizer.state_dict(), + ""epoch"": epoch, + ""step"": step, + } + if self.scheduler is not None: + ckpt[""scheduler""] = self.scheduler.state_dict() + if name is None: + save_name = f""checkpoint_{epoch+1}_{step}.ckpt"" + else: + save_name = name + save_path = os.path.join(self.ckpt_dir, save_name) + torch.save(ckpt, save_path) + logger.info(f""Saved checkpoint: {save_path}"") + if name is None: + self._cleanup_old_checkpoints() + + def _load_checkpoint(self, ckpt_path: str): + map_loc = {""cuda:%d"" % 0: ""cuda:%d"" % self.local_rank} if self.local_rank >= 0 else None + ckpt = torch.load(ckpt_path, map_location=map_loc) + model_sd = ckpt[""model""] + if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): + self.model.module.load_state_dict(model_sd) + else: + self.model.load_state_dict(model_sd) + self.optimizer.load_state_dict(ckpt[""optimizer""]) + if self.scheduler is not None and ckpt.get(""scheduler"") is not None: + self.scheduler.load_state_dict(ckpt[""scheduler""]) + self.start_epoch = ckpt[""epoch""] + 1 + self.global_step = ckpt[""step""] + logger.info(f""Resume from {ckpt_path} | start_epoch={self.start_epoch} step={self.global_step}"") + + def _cleanup_old_checkpoints(self, keep: int = None): + keep = keep if keep is not None else getattr(self.config, 'keep_last_n_checkpoints', 3) + ckpt_files = sorted( + self.ckpt_dir.glob(""checkpoint_*_*.ckpt""), key=os.path.getmtime + ) + for f in ckpt_files[:-keep]: + f.unlink() + + def evaluate(self, step, log: bool = False): + self.model.eval() + logging_infos = [] + with torch.no_grad(): + for batch in self.valid_dataloader: + net_input, net_target = self.decorate_batch(batch) + loss, sample_size, logging_info = self.loss_fn( + self.model, net_input, net_target + ) + logging_infos.append(logging_info) + metrics = self.reduce_metrics( + logging_infos, + writer=self.writer, + logger=logger if log else None, + step=step, + split=""valid"", + unit=""Step"", + ) + self.model.train() + return metrics + + def decorate_batch(self, batch): + # batch is a dict of tensors (batch_size, ...) + device = torch.device(f""cuda:{self.local_rank}"" if torch.cuda.is_available() else ""cpu"") + net_input = { + 'src_tokens': batch['net_input']['src_tokens'].to(device), + 'src_coord': batch['net_input']['src_coord'].to(device), + 'src_distance': batch['net_input']['src_distance'].to(device), + 'src_edge_type': batch['net_input']['src_edge_type'].to(device), + } + net_target = { + 'tgt_tokens': batch['net_target']['tgt_tokens'].to(device), + 'tgt_coordinates': batch['net_target']['tgt_coordinates'].to(device), + 'tgt_distance': batch['net_target']['tgt_distance'].to(device), + } + if self.fp16: + for k in ['src_coord', 'src_distance']: + net_input[k] = net_input[k].half() + for k in ['tgt_coordinates', 'tgt_distance']: + net_target[k] = net_target[k].half() + return net_input, net_target + + def reduce_metrics( + self, + logging_outputs, + writer=None, + logger=None, + step=None, + split=""train"", + unit=""Epoch"", + epoch=None, + inner_step=None, + inner_total=None, + ): + metrics_mean = self.loss_fn.reduce_metrics(logging_outputs, split=split) + if split.startswith(""train"") and self.fp16 and self.scaler is not None: + metrics_mean[""loss_scale""] = self.scaler.loss_scale + if ""bsz"" in metrics_mean: + metrics_mean[""bsz""] *= self.world_size + if writer is not None and step is not None: + if ""loss"" in metrics_mean: + writer.add_scalar(f""{split}/loss"", metrics_mean[""loss""], step) + for k, v in metrics_mean.items(): + if k == ""loss"": + continue + writer.add_scalar(f""{split}/{k}"", v, step) + if logger is not None and step is not None: + log_items = [] + if ""loss"" in metrics_mean: + log_items.append(f""loss={metrics_mean['loss']:.4f}"") + for k, v in metrics_mean.items(): + if k in {""loss"", ""bsz"", ""loss_scale""}: + continue + log_items.append(f""{k}={v:.4f}"") + bsz_val = metrics_mean.get(""bsz"") + if bsz_val is not None: + log_items.append(f""bsz={int(bsz_val)}"") + current_lr = self.optimizer.param_groups[0][""lr""] + log_items.append(f""lr={current_lr:.4e}"") + if split.startswith(""train"") and self.fp16 and self.scaler is not None: + log_items.append(f""loss_scale={self.scaler.loss_scale:.0f}"") + if ( + split == ""train_inner"" + and epoch is not None + and inner_step is not None + and inner_total is not None + ): + logger.info( + f""[{split}] step {step}, epoch {epoch:03d}: {inner_step:6d} / {inner_total}: "" + + "", "".join(log_items) + ) + else: + logger.info(f""[{split}] {unit} {step}: "" + "", "".join(log_items)) + return metrics_mean + +def seed_worker(worker_id): + worker_seed = torch.initial_seed() % 2**32 + random.seed(worker_seed) + np.random.seed(worker_seed)","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/pretrain/loss.py",".py","8557","241","import torch +import torch.nn as nn +import torch.nn.functional as F + +from .metrics import metrics + + +class UniMolLoss(nn.Module): + """"""Pretraining loss for Uni-Mol model. + + This implementation mirrors the original Uni-Mol loss which combines + token, coordinate and distance objectives together with several + regularization terms. + """""" + + def __init__( + self, + dictionary, + masked_token_loss=1, + masked_coord_loss=5, + masked_dist_loss=10, + x_norm_loss=0.01, + delta_pair_repr_norm_loss=0.01, + # Statistics computed from the original Uni-Mol dataset: + # https://github.com/dptech-corp/Uni-Mol/blob/main/unimol/unimol/losses/unimol.py + dist_mean=6.312581655060595, + dist_std=3.3899264663911888, + ): + super().__init__() + self.padding_idx = dictionary.pad() + self.masked_token_loss = masked_token_loss + self.masked_coord_loss = masked_coord_loss + self.masked_dist_loss = masked_dist_loss + self.x_norm_loss = x_norm_loss + self.delta_pair_repr_norm_loss = delta_pair_repr_norm_loss + # statistics used for distance normalization + self.dist_mean = dist_mean + self.dist_std = dist_std + + def forward(self, model, net_input, net_target): + tgt_tokens = net_target[""tgt_tokens""] + tgt_coordinates = net_target[""tgt_coordinates""] + tgt_distance = net_target[""tgt_distance""] + masked_tokens = tgt_tokens.ne(self.padding_idx) + + ( + logits_encoder, + encoder_distance, + encoder_coord, + x_norm, + delta_encoder_pair_rep_norm, + ) = model(**net_input, encoder_masked_tokens=masked_tokens) + + target = tgt_tokens + if masked_tokens is not None: + target = target[masked_tokens] + + masked_token_loss = F.nll_loss( + F.log_softmax(logits_encoder, dim=-1, dtype=torch.float32), + target, + ignore_index=self.padding_idx, + reduction=""mean"", + ) + masked_pred = logits_encoder.argmax(dim=-1) + masked_hit = (masked_pred == target).long().sum() + masked_cnt = masked_tokens.long().sum() + + loss = masked_token_loss * self.masked_token_loss + + logging_output = { + ""sample_size"": 1, + ""bsz"": tgt_tokens.size(0), + ""seq_len"": tgt_tokens.size(0) * tgt_tokens.size(1), + ""masked_token_loss"": masked_token_loss.data, + ""masked_token_hit"": masked_hit.data, + ""masked_token_cnt"": masked_cnt, + } + + if encoder_coord is not None: + coord_target = tgt_coordinates + masked_coord_loss = F.smooth_l1_loss( + encoder_coord[masked_tokens].view(-1, 3).float(), + coord_target[masked_tokens].view(-1, 3), + reduction=""mean"", + beta=1.0, + ) + loss = loss + masked_coord_loss * self.masked_coord_loss + logging_output[""masked_coord_loss""] = masked_coord_loss.data + + if encoder_distance is not None: + masked_dist_loss = self.cal_dist_loss( + encoder_distance, + tgt_distance, + net_input[""src_tokens""], + masked_tokens, + normalize=True, + ) + loss = loss + masked_dist_loss * self.masked_dist_loss + logging_output[""masked_dist_loss""] = masked_dist_loss.data + + if self.x_norm_loss > 0 and x_norm is not None: + loss = loss + self.x_norm_loss * x_norm + logging_output[""x_norm_loss""] = x_norm.data + + if ( + self.delta_pair_repr_norm_loss > 0 + and delta_encoder_pair_rep_norm is not None + ): + loss = ( + loss + self.delta_pair_repr_norm_loss * delta_encoder_pair_rep_norm + ) + logging_output[ + ""delta_pair_repr_norm_loss"" + ] = delta_encoder_pair_rep_norm.data + + logging_output[""loss""] = loss.data + return loss, 1, logging_output + + def cal_dist_loss( + self, + encoder_distance, + tgt_distance, + src_tokens, + masked_tokens, + normalize=False, + ): + dist_masked_tokens = masked_tokens + masked_distance = encoder_distance[dist_masked_tokens, :] + masked_distance_target = tgt_distance[dist_masked_tokens] + + nb_masked_tokens = dist_masked_tokens.sum(dim=-1) + masked_src_tokens = src_tokens.ne(self.padding_idx) + masked_src_tokens_expanded = torch.repeat_interleave( + masked_src_tokens, nb_masked_tokens, dim=0 + ) + + if normalize: + masked_distance_target = ( + masked_distance_target.float() - self.dist_mean + ) / self.dist_std + + masked_dist_loss = F.smooth_l1_loss( + masked_distance[masked_src_tokens_expanded].view(-1).float(), + masked_distance_target[masked_src_tokens_expanded].view(-1), + reduction=""mean"", + beta=1.0, + ) + return masked_dist_loss + + @staticmethod + def logging_outputs_can_be_summed(is_train: bool) -> bool: + """"""Indicate logging outputs are safe to sum across workers."""""" + return True + + @staticmethod + def reduce_metrics(logging_outputs, split=""train""): + """"""Aggregate logging outputs using unicore.metrics"""""" + loss_sum = sum(log.get(""loss"", 0) for log in logging_outputs) + bsz = sum(log.get(""bsz"", 0) for log in logging_outputs) + sample_size = sum(log.get(""sample_size"", 0) for log in logging_outputs) + seq_len = sum(log.get(""seq_len"", 0) for log in logging_outputs) + + result = {} + if sample_size > 0: + result[""loss""] = loss_sum / sample_size + metrics.log_scalar(""loss"", result[""loss""], sample_size, round=3) + if bsz > 0: + result[""bsz""] = bsz + metrics.log_scalar(""bsz"", bsz, round=1) + metrics.log_scalar(""seq_len"", seq_len / bsz, 1, round=3) + + masked_loss = sum( + log.get(""masked_token_loss"", 0) for log in logging_outputs + ) + if sample_size > 0: + result[""masked_token_loss""] = masked_loss / sample_size + metrics.log_scalar( + ""masked_token_loss"", + result[""masked_token_loss""], + sample_size, + round=3, + ) + + masked_hit = sum( + log.get(""masked_token_hit"", 0) for log in logging_outputs + ) + masked_cnt = sum( + log.get(""masked_token_cnt"", 0) for log in logging_outputs + ) + if masked_cnt > 0: + masked_acc = masked_hit / masked_cnt + result[""masked_acc""] = masked_acc + metrics.log_scalar(""masked_acc"", masked_acc, sample_size, round=3) + + masked_coord_loss = sum( + log.get(""masked_coord_loss"", 0) for log in logging_outputs + ) + if masked_coord_loss > 0 and sample_size > 0: + result[""masked_coord_loss""] = masked_coord_loss / sample_size + metrics.log_scalar( + ""masked_coord_loss"", + result[""masked_coord_loss""], + sample_size, + round=3, + ) + + masked_dist_loss = sum( + log.get(""masked_dist_loss"", 0) for log in logging_outputs + ) + if masked_dist_loss > 0 and sample_size > 0: + result[""masked_dist_loss""] = masked_dist_loss / sample_size + metrics.log_scalar( + ""masked_dist_loss"", + result[""masked_dist_loss""], + sample_size, + round=3, + ) + + x_norm_loss = sum(log.get(""x_norm_loss"", 0) for log in logging_outputs) + if x_norm_loss > 0 and sample_size > 0: + result[""x_norm_loss""] = x_norm_loss / sample_size + metrics.log_scalar( + ""x_norm_loss"", result[""x_norm_loss""], sample_size, round=3 + ) + + delta_pair_repr_norm_loss = sum( + log.get(""delta_pair_repr_norm_loss"", 0) for log in logging_outputs + ) + if delta_pair_repr_norm_loss > 0 and sample_size > 0: + result[""delta_pair_repr_norm_loss""] = ( + delta_pair_repr_norm_loss / sample_size + ) + metrics.log_scalar( + ""delta_pair_repr_norm_loss"", + result[""delta_pair_repr_norm_loss""], + sample_size, + round=3, + ) + + return result +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/pretrain/metrics.py",".py","4767","160","""""""Lightweight metrics aggregation inspired by Uni-Core. + +This module provides a small subset of Uni-Core's ``logging.metrics`` +functionality. It supports hierarchical aggregation contexts via a context +manager and allows scalar values to be logged with optional weights. Logged +values can later be retrieved as averages for a given aggregation name. + +The implementation is intentionally minimal but keeps the same public API used +throughout Uni-Mol so existing training code can rely on the familiar +``metrics.log_scalar`` and ``metrics.aggregate`` helpers. +"""""" + +from __future__ import annotations + +import contextlib +import uuid +from collections import OrderedDict +from typing import Dict, Iterable + + +class _AverageMeter: + """"""Tracks a weighted average for a single metric."""""" + + def __init__(self) -> None: + self.sum = 0.0 + self.count = 0.0 + + def update(self, value: float, weight: float) -> None: + self.sum += float(value) * weight + self.count += weight + + def get_value(self) -> float: + return self.sum / self.count if self.count else 0.0 + + def reset(self) -> None: + self.sum = 0.0 + self.count = 0.0 + + +class _Aggregator: + """"""Container holding meters for a particular aggregation context."""""" + + def __init__(self) -> None: + self.meters: Dict[str, _AverageMeter] = {} + + def log_scalar(self, key: str, value: float, weight: float) -> None: + meter = self.meters.setdefault(key, _AverageMeter()) + meter.update(value, weight) + + def get_smoothed_values(self) -> Dict[str, float]: + return {k: m.get_value() for k, m in self.meters.items()} + + def reset(self) -> None: + for m in self.meters.values(): + m.reset() + + +# --------------------------------------------------------------------------- +# Global registry of aggregators and utilities mirroring Uni-Core's API +# --------------------------------------------------------------------------- +_aggregators: ""OrderedDict[str, _Aggregator]"" = OrderedDict() +_active_aggregators: ""OrderedDict[str, _Aggregator]"" = OrderedDict() + + +def reset() -> None: + """"""Reset all metrics aggregators and create the default context."""""" + _aggregators.clear() + _active_aggregators.clear() + default = _Aggregator() + _aggregators[""default""] = default + _active_aggregators[""default""] = default + + +reset() + + +@contextlib.contextmanager +def aggregate(name: str | None = None, new_root: bool = False): + """"""Context manager to aggregate metrics under ``name``. + + Args: + name: Aggregation key. If ``None`` a temporary aggregator is created. + new_root: If ``True`` this context becomes the new root, ignoring any + previously active aggregators. + """""" + + if name is None: + name = str(uuid.uuid4()) + assert name not in _aggregators + agg = _Aggregator() + temp_name = True + else: + agg = _aggregators.setdefault(name, _Aggregator()) + temp_name = False + + if new_root: + backup = _active_aggregators.copy() + _active_aggregators.clear() + + _active_aggregators[name] = agg + try: + yield agg + finally: + _active_aggregators.pop(name, None) + if temp_name: + _aggregators.pop(name, None) + if new_root: + _active_aggregators.clear() + _active_aggregators.update(backup) + + +def _iter_active() -> Iterable[_Aggregator]: + return _active_aggregators.values() + + +def log_scalar(key: str, value: float, weight: float = 1.0, round: int | None = None) -> None: + """"""Log a scalar value to all active aggregators."""""" + + for agg in _iter_active(): + agg.log_scalar(key, value, weight) + + +def get_smoothed_values(name: str) -> Dict[str, float]: + """"""Return the averaged metrics for the given aggregation name."""""" + + if name not in _aggregators: + return {} + return _aggregators[name].get_smoothed_values() + + +def reset_meters(name: str) -> None: + """"""Reset meters for the specified aggregation."""""" + + if name in _aggregators: + _aggregators[name].reset() + + +# --------------------------------------------------------------------------- +# Compatibility layer so callers can ``from metrics import metrics`` and use +# attribute access (e.g. ``metrics.log_scalar``) like in Uni-Core. +# --------------------------------------------------------------------------- +class _MetricsProxy: + aggregate = staticmethod(aggregate) + log_scalar = staticmethod(log_scalar) + get_smoothed_values = staticmethod(get_smoothed_values) + reset_meters = staticmethod(reset_meters) + reset = staticmethod(reset) + + +metrics = _MetricsProxy() + + +__all__ = [ + ""aggregate"", + ""get_smoothed_values"", + ""log_scalar"", + ""reset"", + ""reset_meters"", + ""metrics"", +]","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/pretrain/preprocess.py",".py","16429","514","import os +import pickle +import logging + +import lmdb +import numpy as np +import pandas as pd +from tqdm import tqdm +from rdkit import Chem +import multiprocessing as mp + +from unimol_tools.data import Dictionary +from unimol_tools.data.conformer import inner_smi2coords + +logger = logging.getLogger(__name__) + + +def _accum_dist_stats(coords): + """"""Compute sum and squared sum of pairwise distances for given coordinates."""""" + if isinstance(coords, list): + coord_list = coords + else: + coord_list = [coords] + dist_sum = 0.0 + dist_sq_sum = 0.0 + dist_cnt = 0 + for c in coord_list: + if c is None: + continue + arr = np.asarray(c, dtype=np.float32) + if arr.ndim != 2 or arr.shape[1] != 3: + continue + diff = arr[:, None, :] - arr[None, :, :] + dist = np.linalg.norm(diff, axis=-1) + iu = np.triu_indices(len(arr), k=1) + vals = dist[iu] + dist_sum += vals.sum() + dist_sq_sum += (vals ** 2).sum() + dist_cnt += vals.size + return dist_sum, dist_sq_sum, dist_cnt + + +def _dict_worker(lmdb_path, start, end): + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=True, + lock=False, + readahead=False, + meminit=False, + max_readers=1, + ) + txn = env.begin() + elem = set() + for idx in range(start, end): + data = txn.get(str(idx).encode()) + if data is None: + continue + item = pickle.loads(data) + atoms = item.get(""atoms"") + if atoms: + elem.update(atoms) + env.close() + return elem + +def build_dictionary(lmdb_path, save_path=None, num_workers=1): + """"""Count element types and return a Dictionary. + + Args: + lmdb_path: Path to LMDB dataset. + save_path: Optional output path for the text dictionary file. + num_workers: Number of parallel workers to use. + """""" + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=True, + lock=False, + readahead=False, + meminit=False, + max_readers=256, + ) + txn = env.begin() + length = txn.stat()[""entries""] + env.close() + + elements_set = set() + if num_workers > 1: + chunk = (length + num_workers - 1) // num_workers + args = [ + (lmdb_path, i * chunk, min((i + 1) * chunk, length)) + for i in range(num_workers) + ] + with mp.Pool(num_workers) as pool: + for s in pool.starmap(_dict_worker, args): + elements_set.update(s) + else: + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=True, + lock=False, + readahead=False, + meminit=False, + max_readers=1, + ) + txn = env.begin() + for idx in range(length): + data = txn.get(str(idx).encode()) + if data is None: + continue + item = pickle.loads(data) + atoms = item.get(""atoms"") + if atoms: + elements_set.update(atoms) + env.close() + + special_tokens = [""[PAD]"", ""[CLS]"", ""[SEP]"", ""[UNK]""] + dictionary = special_tokens + sorted(list(elements_set)) + if save_path is None: + save_path = os.path.join(os.path.dirname(lmdb_path), ""dictionary.txt"") + with open(save_path, ""wb"") as f: + np.savetxt(f, dictionary, fmt=""%s"") + return Dictionary.from_list(dictionary) + +def _worker_process_smi(args): + smi, idx, remove_hs, num_conf = args + return process_smi(smi, idx, remove_hs=remove_hs, num_conf=num_conf) + +def write_to_lmdb( + lmdb_path, smi_iter, num_conf=10, remove_hs=False, num_workers=1, total=None +): + logger.info(f""Writing SMILES to {lmdb_path}"") + + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=False, + lock=False, + readahead=False, + meminit=False, + max_readers=1, + map_size=int(100e9), # 100GB + ) + txn_write = env.begin(write=True) + dist_sum_total = 0.0 + dist_sq_sum_total = 0.0 + dist_cnt_total = 0 + processed = 0 + if num_workers > 1: + ctx = mp.get_context(""spawn"") + def gen(): + for idx, smi in enumerate(smi_iter): + yield (smi, idx, remove_hs, num_conf) + with ctx.Pool(num_workers) as pool: + for inner_output in tqdm( + pool.imap_unordered(_worker_process_smi, gen()), total=total + ): + if inner_output is None: + continue + idx, data, dsum, dsqsum, dcnt = inner_output + txn_write.put(str(idx).encode(), data) + dist_sum_total += dsum + dist_sq_sum_total += dsqsum + dist_cnt_total += dcnt + processed += 1 + if processed % 1000 == 0: + txn_write.commit() + txn_write = env.begin(write=True) + else: + for i, smi in enumerate(tqdm(smi_iter, total=total)): + inner_output = process_smi(smi, i, remove_hs=remove_hs, num_conf=num_conf) + if inner_output is not None: + idx, data, dsum, dsqsum, dcnt = inner_output + txn_write.put(str(idx).encode(), data) + dist_sum_total += dsum + dist_sq_sum_total += dsqsum + dist_cnt_total += dcnt + processed += 1 + if processed % 1000 == 0: + txn_write.commit() + txn_write = env.begin(write=True) + logger.info(f""Processed {processed} molecules"") + txn_write.commit() + env.close() + dist_mean = ( + dist_sum_total / dist_cnt_total if dist_cnt_total > 0 else 0.0 + ) + dist_std = ( + np.sqrt(dist_sq_sum_total / dist_cnt_total - dist_mean ** 2) + if dist_cnt_total > 0 + else 1.0 + ) + logger.info( + f""Saved to LMDB: {lmdb_path} (dist_mean={dist_mean:.6f}, dist_std={dist_std:.6f})"" + ) + return lmdb_path, dist_mean, dist_std + +def _worker_process_dict(args): + idx, item = args + data = { + ""idx"": idx, + ""atoms"": item[""atoms""], + ""coordinates"": item[""coordinates""], + } + if ""smi"" in item: + data[""smi""] = item[""smi""] + dsum, dsqsum, dcnt = _accum_dist_stats(item[""coordinates""]) + return idx, pickle.dumps(data), dsum, dsqsum, dcnt + +def write_dicts_to_lmdb(lmdb_path, mol_iter, num_workers=1, total=None): + """"""Write an iterable of pre-generated molecules to LMDB."""""" + logger.info(f""Writing molecule dicts to {lmdb_path}"") + + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=False, + lock=False, + readahead=False, + meminit=False, + max_readers=1, + map_size=int(100e9), + ) + txn_write = env.begin(write=True) + dist_sum_total = 0.0 + dist_sq_sum_total = 0.0 + dist_cnt_total = 0 + processed = 0 + if num_workers > 1: + ctx = mp.get_context(""spawn"") + def gen(): + for idx, item in enumerate(mol_iter): + yield (idx, item) + with ctx.Pool(num_workers) as pool: + for inner_output in tqdm( + pool.imap_unordered(_worker_process_dict, gen()), + total=total, + ): + idx, data, dsum, dsqsum, dcnt = inner_output + txn_write.put(str(idx).encode(), data) + dist_sum_total += dsum + dist_sq_sum_total += dsqsum + dist_cnt_total += dcnt + processed += 1 + if processed % 1000 == 0: + txn_write.commit() + txn_write = env.begin(write=True) + else: + for i, item in enumerate(tqdm(mol_iter, total=total)): + data = { + ""idx"": i, + ""atoms"": item[""atoms""], + ""coordinates"": item[""coordinates""], + } + if ""smi"" in item: + data[""smi""] = item[""smi""] + txn_write.put(str(i).encode(), pickle.dumps(data)) + dsum, dsqsum, dcnt = _accum_dist_stats(item[""coordinates""]) + dist_sum_total += dsum + dist_sq_sum_total += dsqsum + dist_cnt_total += dcnt + processed += 1 + if processed % 1000 == 0: + txn_write.commit() + txn_write = env.begin(write=True) + logger.info(f""Processed {processed} molecules"") + txn_write.commit() + env.close() + dist_mean = ( + dist_sum_total / dist_cnt_total if dist_cnt_total > 0 else 0.0 + ) + dist_std = ( + np.sqrt(dist_sq_sum_total / dist_cnt_total - dist_mean ** 2) + if dist_cnt_total > 0 + else 1.0 + ) + logger.info( + f""Saved to LMDB: {lmdb_path} (dist_mean={dist_mean:.6f}, dist_std={dist_std:.6f})"" + ) + return lmdb_path, dist_mean, dist_std + +def process_smi(smi, idx, remove_hs=False, num_conf=10, **params): + """"""Process a single SMILES string and return index and serialized data."""""" + conformers = [] + for i in range(num_conf): + atoms, coordinates, _ = inner_smi2coords( + smi, seed=42 + i, mode=""fast"", remove_hs=remove_hs + ) + conformers.append(coordinates) + data = { + ""idx"": idx, + ""atoms"": atoms, + ""coordinates"": conformers if num_conf > 1 else conformers[0], + ""smi"": smi, + } + + dsum, dsqsum, dcnt = _accum_dist_stats(data[""coordinates""]) + + return idx, pickle.dumps(data), dsum, dsqsum, dcnt + +def iter_smi_file(file_path): + """"""Yield SMILES strings from a text file one at a time."""""" + with open(file_path, ""r"") as f: + for line in f: + line = line.strip() + if line: + yield line + +def iter_csv_file(csv_path, smiles_col=""smi"", chunksize=10000): + """"""Yield SMILES strings from a CSV file in chunks."""""" + for chunk in pd.read_csv(csv_path, chunksize=chunksize): + if smiles_col not in chunk.columns: + raise ValueError(f""Column '{smiles_col}' not found in CSV file."") + for smi in chunk[smiles_col].astype(str): + smi = smi.strip() + if smi: + yield smi + +def iter_sdf_file(file_path, remove_hs=False): + """"""Yield molecule dicts from an SDF file without loading everything into memory."""""" + supplier = Chem.SDMolSupplier(file_path, removeHs=False) + for mol in supplier: + if mol is None: + continue + if remove_hs: + mol = Chem.RemoveHs(mol) + atoms = [atom.GetSymbol() for atom in mol.GetAtoms()] + conf = mol.GetConformer() + coords = conf.GetPositions().astype(np.float32) + smi = Chem.MolToSmiles(mol) + yield {""atoms"": atoms, ""coordinates"": coords, ""smi"": smi} + +def count_input_data(data, data_type=""csv"", smiles_col=""smi""): + """"""Return the number of molecules in a non-LMDB dataset."""""" + if data_type in [""smi"", ""txt""]: + with open(data, ""r"") as f: + return sum(1 for line in f if line.strip()) + elif data_type == ""csv"": + count = 0 + for chunk in pd.read_csv(data, usecols=[smiles_col], chunksize=100000): + count += chunk.shape[0] + return count + elif data_type == ""sdf"": + supplier = Chem.SDMolSupplier(data, removeHs=False) + return sum(1 for mol in supplier if mol is not None) + elif data_type == ""list"": + return len(data) if hasattr(data, ""__len__"") else sum(1 for _ in data) + else: + raise ValueError(f""Unsupported data_type: {data_type}"") + +def count_lmdb_entries(lmdb_path): + """"""Return the number of entries stored in an LMDB file."""""" + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=True, + lock=False, + readahead=False, + meminit=False, + max_readers=256, + ) + txn = env.begin() + length = txn.stat()[""entries""] + env.close() + return length + +def preprocess_dataset( + data, + lmdb_path, + data_type=""smi"", + smiles_col=""smi"", + num_conf=10, + remove_hs=False, + num_workers=1, +): + """"""Preprocess various dataset formats into an LMDB file. + + Args: + data: Input data; can be path or list depending on ``data_type``. + lmdb_path: Path to the output LMDB file. + data_type: Format of the input data. Supported values are + ``'smi'``/``'txt'`` for a file with one SMILES per line, + ``'csv'`` for CSV files, ``'sdf'`` for SDF molecule files, + ``'list'`` for a Python list of SMILES strings. + smiles_col: Column name used when ``data_type='csv'``. + num_workers: Number of worker processes used for preprocessing. + """""" + logger.info(f""Preprocessing data of type '{data_type}' to {lmdb_path}"") + if data_type in [""smi"", ""txt""]: + total = count_input_data(data, data_type) + return write_to_lmdb( + lmdb_path, + iter_smi_file(data), + num_conf=num_conf, + remove_hs=remove_hs, + num_workers=num_workers, + total=total, + ) + elif data_type == ""csv"": + total = count_input_data(data, ""csv"", smiles_col) + return write_to_lmdb( + lmdb_path, + iter_csv_file(data, smiles_col=smiles_col), + num_conf=num_conf, + remove_hs=remove_hs, + num_workers=num_workers, + total=total, + ) + elif data_type == ""sdf"": + total = count_input_data(data, ""sdf"") + return write_dicts_to_lmdb( + lmdb_path, + iter_sdf_file(data, remove_hs=remove_hs), + num_workers=num_workers, + total=total, + ) + elif data_type == ""list"": + total = len(data) if hasattr(data, ""__len__"") else None + return write_to_lmdb( + lmdb_path, + iter(data), + num_conf=num_conf, + remove_hs=remove_hs, + num_workers=num_workers, + total=total, + ) + else: + raise ValueError(f""Unsupported data_type: {data_type}"") + +def _dist_worker(lmdb_path, start, end): + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=True, + lock=False, + readahead=False, + meminit=False, + max_readers=1, + ) + txn = env.begin() + dsum = dsqsum = dcnt = 0.0 + for idx in range(start, end): + data = txn.get(str(idx).encode()) + if data is None: + continue + item = pickle.loads(data) + a, b, c = _accum_dist_stats(item.get(""coordinates"")) + dsum += a + dsqsum += b + dcnt += c + env.close() + return dsum, dsqsum, dcnt + +def compute_lmdb_dist_stats(lmdb_path, num_workers=1): + """"""Compute distance mean and std from an existing LMDB dataset."""""" + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=True, + lock=False, + readahead=False, + meminit=False, + max_readers=256, + ) + txn = env.begin() + length = txn.stat()[""entries""] + env.close() + + dist_sum_total = 0.0 + dist_sq_sum_total = 0.0 + dist_cnt_total = 0.0 + if num_workers > 1: + chunk = (length + num_workers - 1) // num_workers + args = [ + (lmdb_path, i * chunk, min((i + 1) * chunk, length)) + for i in range(num_workers) + ] + with mp.Pool(num_workers) as pool: + for dsum, dsqsum, dcnt in pool.starmap(_dist_worker, args): + dist_sum_total += dsum + dist_sq_sum_total += dsqsum + dist_cnt_total += dcnt + else: + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=True, + lock=False, + readahead=False, + meminit=False, + max_readers=1, + ) + txn = env.begin() + for idx in range(length): + data = txn.get(str(idx).encode()) + if data is None: + continue + item = pickle.loads(data) + dsum, dsqsum, dcnt = _accum_dist_stats(item.get(""coordinates"")) + dist_sum_total += dsum + dist_sq_sum_total += dsqsum + dist_cnt_total += dcnt + env.close() + + dist_mean = dist_sum_total / dist_cnt_total if dist_cnt_total > 0 else 0.0 + dist_std = ( + np.sqrt(dist_sq_sum_total / dist_cnt_total - dist_mean ** 2) + if dist_cnt_total > 0 + else 1.0 + ) + logger.info(f""dist_mean={dist_mean:.6f}, dist_std={dist_std:.6f}"") + return dist_mean, dist_std +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/pretrain/dataset.py",".py","10617","320","import logging +import pickle +from functools import lru_cache + +import lmdb +import numpy as np +import torch +from torch.utils.data import Dataset +from rdkit import Chem +from rdkit.Chem import AllChem + +from .data_utils import numpy_seed + +logger = logging.getLogger(__name__) + +def smi2_2dcoords(smiles, atoms=None): + mol = Chem.MolFromSmiles(smiles) + if mol is None: + raise ValueError(f""Invalid SMILES string: {smiles}"") + try: + mol = AllChem.AddHs(mol) + AllChem.Compute2DCoords(mol) + except Exception as exc: # pragma: no cover - RDKit exceptions are varied + raise ValueError(f""Failed to compute 2D coordinates for '{smiles}': {exc}"") + rdkit_atoms = [a.GetSymbol() for a in mol.GetAtoms()] + coordinates = mol.GetConformer().GetPositions().astype(np.float32) + + if atoms is not None and len(rdkit_atoms) != len(atoms): + mask = [sym != ""H"" for sym in rdkit_atoms] + coordinates = coordinates[mask] + rdkit_atoms = [sym for sym in rdkit_atoms if sym != ""H""] + + if atoms is not None and len(rdkit_atoms) != len(atoms): + raise ValueError( + f""2D atom count {len(rdkit_atoms)} does not match LMDB atoms {len(atoms)}"" + ) + + assert len(rdkit_atoms) == len(coordinates) + return coordinates + + +class LMDBDataset(Dataset): + """""" + Read LMDB and output idx, element types, atomic numbers, and 3D coordinates. Supports caching. + """""" + def __init__(self, lmdb_path): + env = lmdb.open( + lmdb_path, + subdir=False, + readonly=True, + lock=False, + readahead=False, + meminit=False, + max_readers=256, + ) + self.txn = env.begin() + self.length = self.txn.stat()['entries'] + + def __len__(self): + return self.length + + def __getitem__(self, idx): + data = self.txn.get(str(idx).encode()) + if data is None: + raise IndexError(f""Index {idx} not found in LMDB."") + item = pickle.loads(data) + atoms = item.get('atoms') + coordinates = item.get('coordinates') + + result = { + 'idx': item.get('idx'), + 'atoms': atoms, + 'coordinates': coordinates, + 'smi': item.get('smi'), + } + return result + +class UniMolDataset(Dataset): + """"""Wraps an LMDBDataset and samples 3D or on-the-fly 2D conformers."""""" + + def __init__( + self, + lmdb_dataset, + dictionary, + remove_hs=False, + max_atoms=256, + seed=1, + sample_conformer=True, + add_2d=True, + **params, + ): + self.dataset = lmdb_dataset + self.length = len(self.dataset) + self.dictionary = dictionary + self.remove_hs = remove_hs + self.max_atoms = max_atoms + self.seed = seed + self.sample_conformer = sample_conformer + self.add_2d = add_2d + self.params = params + self.mask_id = dictionary.add_symbol(""[MASK]"", is_special=True) + self.set_epoch(0) # Initialize epoch to 0 + + def __len__(self): + return self.length + + def set_epoch(self, epoch): + self.epoch = epoch + with numpy_seed(self.seed, epoch): + self.sort_order = np.random.permutation(self.length) + + def ordered_indices(self): + return self.sort_order + + + def __getitem__(self, idx): + return self.__getitem__cached__(self.epoch, idx) + + @lru_cache(maxsize=16) + def __getitem__cached__(self, epoch, idx): + item = self.dataset[idx] + atoms = item[""atoms""] + coordinates = item[""coordinates""] + + if atoms is None or coordinates is None: + raise ValueError( + f""Invalid data at index {idx}: atoms or coordinates are None."" + ) + + coord_list = list(coordinates) if isinstance(coordinates, list) else [coordinates] + if self.add_2d and item.get(""smi"") is not None: + try: + coord_list.append(smi2_2dcoords(item[""smi""], atoms)) + except ValueError as exc: + logger.warning( + ""[UniMolDataset] failed to add 2D conformer for idx %s: %s"", + idx, + exc, + ) + + with numpy_seed(self.seed, epoch, idx): + sel = np.random.randint(len(coord_list)) if self.sample_conformer else 0 + coordinates = coord_list[sel] + + net_input, target = coords2unimol( + atoms=atoms, + coordinates=coordinates, + dictionary=self.dictionary, + mask_id=self.mask_id, + noise_type=self.params.get(""noise_type"", ""uniform""), + noise=self.params.get(""noise"", 1.0), + seed=self.params.get(""seed"", 1), + epoch=epoch, + index=idx, + mask_prob=self.params.get(""mask_prob"", 0.15), + leave_unmasked_prob=self.params.get(""leave_unmasked_prob"", 0.05), + random_token_prob=self.params.get(""random_token_prob"", 0.05), + max_atoms=self.max_atoms, + remove_hs=self.remove_hs, + ) + return net_input, target + +def coords2unimol( + atoms, + coordinates, + dictionary, + mask_id, + noise_type, + noise=1.0, + seed=1, + epoch=0, + index=0, + mask_prob=0.15, + leave_unmasked_prob=0.05, + random_token_prob=0.05, + max_atoms=256, + remove_hs=True, + **params, +): + with numpy_seed(seed, epoch, index): + assert len(atoms) == len(coordinates), ""coordinates shape does not align with atoms"" + coordinates = torch.tensor(coordinates, dtype=torch.float32) + if remove_hs: + idx = [i for i, atom in enumerate(atoms) if atom != ""H""] + atoms_no_h = [atom for atom in atoms if atom != ""H""] + coordinates_no_h = coordinates[idx] + assert ( + len(atoms_no_h) == len(coordinates_no_h) + ), ""coordinates shape is not align with atoms"" + atoms, coordinates = atoms_no_h, coordinates_no_h + + # Crop atoms and coordinates if exceeding max_atoms + if len(atoms) > max_atoms: + sel = np.random.choice(len(atoms), max_atoms, replace=False) + atoms = [atoms[i] for i in sel] + coordinates = coordinates[sel] + + # Normalize coordinates + coordinates = coordinates - coordinates.mean(dim=0) + + # Add noise and mask + src_tokens, src_coord, tgt_tokens = apply_noise_and_mask( + src_tokens=torch.tensor( + [dictionary.index(atom) for atom in atoms], dtype=torch.long + ), + coordinates=coordinates, + dictionary=dictionary, + mask_id=mask_id, + noise_type=noise_type, + noise=noise, + mask_prob=mask_prob, + leave_unmasked_prob=leave_unmasked_prob, + random_token_prob=random_token_prob, + ) + + # Pad tokens + src_tokens = torch.cat([torch.tensor([dictionary.bos()]), src_tokens, torch.tensor([dictionary.eos()])], dim=0) + tgt_tokens = torch.cat([torch.tensor([dictionary.pad()]), tgt_tokens, torch.tensor([dictionary.pad()])], dim=0) + + # Pad coordinates + pad = torch.zeros((1, 3), dtype=torch.float32) + src_coord = torch.cat([pad, src_coord, pad], dim=0) + tgt_coordinates = torch.cat([pad, coordinates, pad], dim=0) + + # Calculate distance matrix + diff = src_coord.unsqueeze(0) - src_coord.unsqueeze(1) + src_distance = torch.norm(diff, dim=-1) + tgt_distance = torch.norm(tgt_coordinates.unsqueeze(0) - tgt_coordinates.unsqueeze(1), dim=-1) + + # Calculate edge type + src_edge_type = src_tokens.view(-1, 1) * len(dictionary) + src_tokens.view(1, -1) + + return { + ""src_tokens"": src_tokens, + ""src_coord"": src_coord, + ""src_distance"": src_distance, + ""src_edge_type"": src_edge_type, + }, { + ""tgt_tokens"": tgt_tokens, + ""tgt_coordinates"": tgt_coordinates, + ""tgt_distance"": tgt_distance, + } + + +def apply_noise_and_mask( + src_tokens, + coordinates, + dictionary, + mask_id, + noise_type, + noise=1.0, + mask_prob=0.15, + leave_unmasked_prob=0.05, + random_token_prob=0.05 + ): + """""" + Apply noise and masking to the source tokens. + """""" + if random_token_prob > 0: + weights = np.ones(len(dictionary)) + weights[dictionary.special_index()] = 0 + weights /= weights.sum() + + sz = len(src_tokens) + assert sz > 0, ""Source tokens must not be empty."" + + num_mask = int(sz * mask_prob + np.random.rand()) + mask_idc = np.random.choice(sz, num_mask, replace=False) + mask = np.full(sz, fill_value=False) + mask[mask_idc] = True + + tgt_tokens = np.full(sz, dictionary.pad()) + tgt_tokens[mask] = src_tokens[mask] + tgt_tokens = torch.from_numpy(tgt_tokens).long() + + # Determine unmasked and random tokens + rand_or_unmask_prob = random_token_prob + leave_unmasked_prob + if rand_or_unmask_prob > 0: + rand_or_unmask = mask & (np.random.rand(sz) < rand_or_unmask_prob) + if random_token_prob == 0: + unmasked = rand_or_unmask + rand_mask = None + elif leave_unmasked_prob == 0: + unmasked = None + rand_mask = rand_or_unmask + else: + unmask_prob = leave_unmasked_prob / rand_or_unmask_prob + unmasked = rand_or_unmask & (np.random.rand(sz) < unmask_prob) + rand_mask = rand_or_unmask & ~unmasked + else: + unmasked = None + rand_mask = None + + if unmasked is not None: + mask = mask ^ unmasked + + new_src_tokens = src_tokens.clone() + new_src_tokens[mask] = mask_id + + num_mask = mask.sum().item() + new_coordinates = coordinates.clone() + + # Add noise to masked coordinates + if noise_type == ""trunc_normal"": + noise_f = np.clip(np.random.randn(num_mask, 3) * noise, -noise*2, noise*2) + elif noise_type == ""normal"": + noise_f = np.random.randn(num_mask, 3) * noise + elif noise_type == ""uniform"": + noise_f = np.random.uniform(-noise, noise, size=(num_mask, 3)) + else: + noise_f = np.zeros((num_mask, 3), dtype=np.float32) + new_coordinates[mask, :] += torch.tensor(noise_f, dtype=torch.float32) + + if rand_mask is not None: + num_rand = rand_mask.sum() + if num_rand > 0: + new_src_tokens[rand_mask] = torch.tensor( + np.random.choice(len(dictionary), num_rand, p=weights), dtype=torch.long + ) + return new_src_tokens, new_coordinates, tgt_tokens","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/pretrain/unimol.py",".py","9566","270","import random + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ..models.transformers import ( + TransformerEncoderWithPair, + get_activation_fn, + init_bert_params, +) +from ..utils import pad_1d_tokens, pad_2d, pad_coords + + +class UniMolModel(nn.Module): + def __init__(self, config, dictionary): + super(UniMolModel, self).__init__() + self.config = config + self.dictionary = dictionary + self.padding_idx = dictionary.pad() + self.embed_tokens = nn.Embedding(len(dictionary), config.encoder_embed_dim, padding_idx=self.padding_idx) + self.encoder = TransformerEncoderWithPair( + encoder_layers=config.encoder_layers, + embed_dim=config.encoder_embed_dim, + ffn_embed_dim=config.encoder_ffn_embed_dim, + attention_heads=config.encoder_attention_heads, + emb_dropout=config.emb_dropout, + dropout=config.dropout, + attention_dropout=config.attention_dropout, + activation_dropout=config.activation_dropout, + max_seq_len=config.max_seq_len, + activation_fn=config.activation_fn, + no_final_head_layer_norm=config.delta_pair_repr_norm_loss < 0, + ) + + K = 128 + n_edge_type = len(dictionary) * len(dictionary) + self.gbf_proj = NonLinearHead( + K, config.encoder_attention_heads, config.activation_fn + ) + self.gbf = GaussianLayer(K, n_edge_type) + + if config.masked_token_loss > 0: + self.lm_head = MaskLMHead( + embed_dim=config.encoder_embed_dim, + output_dim=len(dictionary), + activation_fn=config.activation_fn, + weight=None, + ) + if config.masked_coord_loss > 0: + self.pair2coord_proj = NonLinearHead( + config.encoder_attention_heads, 1, config.activation_fn + ) + if config.masked_dist_loss > 0: + self.dist_head = DistanceHead( + config.encoder_attention_heads, config.activation_fn + ) + self.classification_heads = nn.ModuleDict() + self.apply(init_bert_params) + + def forward( + self, + src_tokens, + src_distance, + src_coord, + src_edge_type, + encoder_masked_tokens=None, + **params + ): + + padding_mask = src_tokens.eq(self.padding_idx) + if not padding_mask.any(): + padding_mask = None + x = self.embed_tokens(src_tokens) + + def get_dist_features(dist, et): + n_node = dist.size(-1) + gbf_feature = self.gbf(dist, et) + gbf_result = self.gbf_proj(gbf_feature) + graph_attn_bias = gbf_result + graph_attn_bias = graph_attn_bias.permute(0, 3, 1, 2).contiguous() + graph_attn_bias = graph_attn_bias.view(-1, n_node, n_node) + return graph_attn_bias + + graph_attn_bias = get_dist_features(src_distance, src_edge_type) + ( + encoder_rep, + encoder_pair_rep, + delta_encoder_pair_rep, + x_norm, + delta_encoder_pair_rep_norm, + ) = self.encoder(x, padding_mask=padding_mask, attn_mask=graph_attn_bias) + encoder_pair_rep[encoder_pair_rep == float(""-inf"")] = 0 + + encoder_distance = None + encoder_coord = None + + if self.config.masked_token_loss > 0: + logits = self.lm_head(encoder_rep, encoder_masked_tokens) + if self.config.masked_coord_loss > 0: + coords_emb = src_coord + if padding_mask is not None: + atom_num = torch.sum(1 - padding_mask.type_as(x), dim=1).view( + -1, 1, 1, 1 + ) # consider BOS and EOS as part of the object + else: + atom_num = src_coord.shape[1] + delta_pos = coords_emb.unsqueeze(1) - coords_emb.unsqueeze(2) + attn_probs = self.pair2coord_proj(delta_encoder_pair_rep) + coord_update = delta_pos / atom_num * attn_probs + # Mask padding + pair_coords_mask = (1 - padding_mask.float()).unsqueeze(-1) * (1 - padding_mask.float()).unsqueeze(1) + coord_update = coord_update * pair_coords_mask.unsqueeze(-1) + # + coord_update = torch.sum(coord_update, dim=2) + encoder_coord = coords_emb + coord_update + if self.config.masked_dist_loss > 0: + encoder_distance = self.dist_head(encoder_pair_rep) + + return ( + logits, + encoder_distance, + encoder_coord, + x_norm, + delta_encoder_pair_rep_norm, + ) + + def batch_collate_fn(self, batch): + net_input = { + 'src_tokens': pad_1d_tokens([item[0]['src_tokens'] for item in batch], self.padding_idx), + 'src_coord': pad_coords([item[0]['src_coord'] for item in batch], pad_idx=0.0), + 'src_distance': pad_2d([item[0]['src_distance'] for item in batch], pad_idx=0.0), + 'src_edge_type': pad_2d([item[0]['src_edge_type'] for item in batch], pad_idx=0), + } + net_target = { + 'tgt_tokens': pad_1d_tokens([item[1]['tgt_tokens'] for item in batch], self.padding_idx), + 'tgt_coordinates': pad_coords([item[1]['tgt_coordinates'] for item in batch], pad_idx=0.0), + 'tgt_distance': pad_2d([item[1]['tgt_distance'] for item in batch], pad_idx=0.0), + } + return {'net_input': net_input, 'net_target': net_target} + +class MaskLMHead(nn.Module): + """"""Head for masked language modeling."""""" + + def __init__(self, embed_dim, output_dim, activation_fn, weight=None): + super().__init__() + self.dense = nn.Linear(embed_dim, embed_dim) + self.activation_fn = get_activation_fn(activation_fn) + self.layer_norm = nn.LayerNorm(embed_dim) + + if weight is None: + weight = nn.Linear(embed_dim, output_dim, bias=False).weight + self.weight = weight + self.bias = nn.Parameter(torch.zeros(output_dim)) + + def forward(self, features, masked_tokens=None, **kwconfig): + # Only project the masked tokens while training, + # saves both memory and computation + if masked_tokens is not None: + features = features[masked_tokens, :] + + x = self.dense(features) + x = self.activation_fn(x) + x = self.layer_norm(x) + # project back to size of vocabulary with bias + x = F.linear(x, self.weight) + self.bias + return x + +class ClassificationHead(nn.Module): + """"""Head for sentence-level classification tasks."""""" + + def __init__( + self, + input_dim, + inner_dim, + num_classes, + activation_fn, + pooler_dropout, + ): + super().__init__() + self.dense = nn.Linear(input_dim, inner_dim) + self.activation_fn = get_activation_fn(activation_fn) + self.dropout = nn.Dropout(p=pooler_dropout) + self.out_proj = nn.Linear(inner_dim, num_classes) + + def forward(self, features, **kwconfig): + x = features[:, 0, :] # take token (equiv. to [CLS]) + x = self.dropout(x) + x = self.dense(x) + x = self.activation_fn(x) + x = self.dropout(x) + x = self.out_proj(x) + return x + + +class NonLinearHead(nn.Module): + """"""Head for simple classification tasks."""""" + + def __init__( + self, + input_dim, + out_dim, + activation_fn, + hidden=None, + ): + super().__init__() + hidden = input_dim if not hidden else hidden + self.linear1 = nn.Linear(input_dim, hidden) + self.linear2 = nn.Linear(hidden, out_dim) + self.activation_fn = get_activation_fn(activation_fn) + + def forward(self, x): + x = self.linear1(x) + x = self.activation_fn(x) + x = self.linear2(x) + return x + + +class DistanceHead(nn.Module): + def __init__( + self, + heads, + activation_fn, + ): + super().__init__() + self.dense = nn.Linear(heads, heads) + self.layer_norm = nn.LayerNorm(heads) + self.out_proj = nn.Linear(heads, 1) + self.activation_fn = get_activation_fn(activation_fn) + + def forward(self, x): + bsz, seq_len, seq_len, _ = x.size() + # x[x == float('-inf')] = 0 + x = self.dense(x) + x = self.activation_fn(x) + x = self.layer_norm(x) + x = self.out_proj(x).view(bsz, seq_len, seq_len) + x = (x + x.transpose(-1, -2)) * 0.5 + return x + + +@torch.jit.script +def gaussian(x, mean, std): + pi = 3.14159 + a = (2 * pi) ** 0.5 + return torch.exp(-0.5 * (((x - mean) / std) ** 2)) / (a * std) + + +class GaussianLayer(nn.Module): + def __init__(self, K=128, edge_types=1024): + super().__init__() + self.K = K + self.means = nn.Embedding(1, K) + self.stds = nn.Embedding(1, K) + self.mul = nn.Embedding(edge_types, 1) + self.bias = nn.Embedding(edge_types, 1) + nn.init.uniform_(self.means.weight, 0, 3) + nn.init.uniform_(self.stds.weight, 0, 3) + nn.init.constant_(self.bias.weight, 0) + nn.init.constant_(self.mul.weight, 1) + + def forward(self, x, edge_type): + mul = self.mul(edge_type).type_as(x) + bias = self.bias(edge_type).type_as(x) + x = mul * x.unsqueeze(-1) + bias + x = x.expand(-1, -1, -1, self.K) + mean = self.means.weight.float().view(-1) + std = self.stds.weight.float().view(-1).abs() + 1e-5 + return gaussian(x.float(), mean, std).type_as(self.means.weight) +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/pretrain/__init__.py",".py","345","13","from .dataset import LMDBDataset, UniMolDataset +from .loss import UniMolLoss +from .preprocess import ( + build_dictionary, + preprocess_dataset, + compute_lmdb_dist_stats, + count_input_data, + count_lmdb_entries, +) +from .pretrain_config import PretrainConfig +from .trainer import UniMolPretrainTrainer +from .unimol import UniMolModel +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/pretrain/pretrain_config.py",".py","9708","277","from dataclasses import dataclass, field +from typing import Optional, Tuple + +from hydra.core.config_store import ConfigStore + + +@dataclass +class DatasetConfig: + train_path: str = field( + default="""", + metadata={""help"": ""Path to the training dataset.""}, + ) + valid_path: Optional[str] = field( + default=None, + metadata={""help"": ""Path to the validation dataset.""}, + ) + data_type: str = field( + default=""lmdb"", + metadata={""help"": ""Dataset format, e.g. 'lmdb', 'csv', 'txt', 'smi', or 'sdf'.""}, + ) + smiles_column: str = field( + default=""smi"", + metadata={""help"": ""Column name for SMILES when reading CSV data.""}, + ) + dict_path: Optional[str] = field( + default=None, + metadata={""help"": ""Optional path to the dictionary file.""}, + ) + remove_hydrogen: bool = field( + default=False, + metadata={""help"": ""Remove hydrogen atoms from molecules.""}, + ) + max_atoms: int = field( + default=256, + metadata={""help"": ""Maximum number of atoms per molecule.""}, + ) + noise_type: str = field( + default=""uniform"", + metadata={""help"": ""Type of noise added to coordinates during masking.""}, + ) + noise: float = field( + default=1.0, + metadata={""help"": ""Magnitude of coordinate noise.""}, + ) + mask_prob: float = field( + default=0.15, + metadata={""help"": ""Probability of masking an atom token.""}, + ) + leave_unmasked_prob: float = field( + default=0.05, + metadata={""help"": ""Probability of keeping a masked token unchanged.""}, + ) + random_token_prob: float = field( + default=0.05, + metadata={""help"": ""Probability of replacing a masked token with a random token.""}, + ) + add_2d: bool = field( + default=True, + metadata={""help"": ""Append a 2D conformer generated from the SMILES string at runtime.""}, + ) + num_conformers: int = field( + default=10, + metadata={""help"": ""Number of 3D conformers to generate per molecule during preprocessing.""}, + ) + preprocess_workers: int = field( + default=8, + metadata={ + ""help"": ""Number of worker processes to use when converting datasets to LMDB."" + }, + ) + stats_workers: int = field( + default=8, + metadata={ + ""help"": ""Number of CPU workers to scan LMDBs for building dictionaries and distance statistics."" + }, + ) + +@dataclass +class ModelConfig: + model_name: str = field( + default=""UniMol"", + metadata={""help"": ""Model architecture to use.""}, + ) + encoder_layers: int = field( + default=15, + metadata={""help"": ""Number of transformer encoder layers.""}, + ) + encoder_embed_dim: int = field( + default=512, + metadata={""help"": ""Embedding dimension of the encoder.""}, + ) + encoder_ffn_embed_dim: int = field( + default=2048, + metadata={""help"": ""Hidden dimension of the encoder feed-forward network.""}, + ) + encoder_attention_heads: int = field( + default=64, + metadata={""help"": ""Number of attention heads in the encoder.""}, + ) + dropout: float = field( + default=0.1, + metadata={""help"": ""Dropout rate applied after the feed-forward network.""}, + ) + emb_dropout: float = field( + default=0.1, + metadata={""help"": ""Dropout rate applied to embeddings.""}, + ) + attention_dropout: float = field( + default=0.1, + metadata={""help"": ""Dropout rate for attention weights.""}, + ) + activation_dropout: float = field( + default=0.0, + metadata={""help"": ""Dropout after activation in the feed-forward network.""}, + ) + pooler_dropout: float = field( + default=0.0, + metadata={""help"": ""Dropout applied in the pooling layer.""}, + ) + max_seq_len: int = field( + default=512, + metadata={""help"": ""Maximum input sequence length.""}, + ) + activation_fn: str = field( + default=""gelu"", + metadata={""help"": ""Activation function for the feed-forward network.""}, + ) + pooler_activation_fn: str = field( + default=""tanh"", + metadata={""help"": ""Activation function for the pooling layer.""}, + ) + post_ln: bool = field( + default=False, + metadata={""help"": ""Use Post-LayerNorm instead of Pre-LayerNorm.""}, + ) + masked_token_loss: float = field( + default=1.0, + metadata={""help"": ""Weight of the masked token prediction loss.""}, + ) + masked_coord_loss: float = field( + default=5.0, + metadata={""help"": ""Weight of the masked coordinate prediction loss.""}, + ) + masked_dist_loss: float = field( + default=10.0, + metadata={""help"": ""Weight of the masked distance prediction loss.""}, + ) + x_norm_loss: float = field( + default=0.01, + metadata={""help"": ""Weight of the atom-wise representation norm regularization.""}, + ) + delta_pair_repr_norm_loss: float = field( + default=0.01, + metadata={""help"": ""Weight of the pair representation difference norm regularization.""}, + ) + +@dataclass +class TrainingConfig: + batch_size: int = field( + default=16, + metadata={""help"": ""Per-GPU batch size; effective batch size is n_gpu * batch_size * update_freq.""}, + ) + update_freq: int = field( + default=1, + metadata={""help"": ""Number of steps to accumulate gradients before updating (update frequency).""}, + ) + lr: float = field( + default=1e-4, + metadata={""help"": ""Initial learning rate.""}, + ) + weight_decay: float = field( + default=1e-4, + metadata={""help"": ""Weight decay for Adam optimizer.""}, + ) + adam_betas: Tuple[float, float] = field( + default=(0.9, 0.99), + metadata={""help"": ""Beta coefficients for Adam optimizer.""}, + ) + adam_eps: float = field( + default=1e-6, + metadata={""help"": ""Epsilon for Adam optimizer.""}, + ) + clip_grad_norm: float = field( + default=1.0, + metadata={""help"": ""Maximum gradient norm for clipping.""}, + ) + epochs: int = field( + default=0, + metadata={""help"": ""Number of epochs; 0 to disable and rely on total_steps.""}, + ) + total_steps: int = field( + default=1000000, + metadata={""help"": ""Maximum number of optimizer update steps.""}, + ) + warmup_steps: int = field( + default=10000, + metadata={""help"": ""Number of steps to linearly warm up the learning rate.""}, + ) + log_every_n_steps: int = field( + default=10, + metadata={""help"": ""Log training metrics every N update steps.""}, + ) + save_every_n_steps: int = field( + default=10000, + metadata={""help"": ""Save a checkpoint every N update steps.""}, + ) + keep_last_n_checkpoints: int = field( + default=5, + metadata={""help"": ""How many step checkpoints to keep.""}, + ) + patience: int = field( + default=-1, + metadata={""help"": ""Early stop patience based on validation loss; -1 disables.""}, + ) + fp16: bool = field( + default=True, + metadata={""help"": ""Use fp16 mixed precision training.""}, + ) + fp16_init_scale: float = field( + default=4, + metadata={""help"": ""Initial loss scale for fp16 training.""}, + ) + fp16_scale_window: int = field( + default=256, + metadata={""help"": ""Steps without overflow before increasing the loss scale.""}, + ) + num_workers: int = field( + default=8, + metadata={""help"": ""Number of worker processes for data loading.""}, + ) + seed: int = field( + default=42, + metadata={""help"": ""Random seed.""}, + ) + resume: Optional[str] = field( + default=None, + metadata={""help"": ""Path to a checkpoint to resume training from.""}, + ) + output_dir: Optional[str] = field( + default=None, + metadata={""help"": ""Directory to save checkpoints and logs.""}, + ) + +@dataclass +class PretrainConfig: + dataset: DatasetConfig = field(default_factory=DatasetConfig) + model: ModelConfig = field(default_factory=ModelConfig) + training: TrainingConfig = field(default_factory=TrainingConfig) + + def validate(self): + if not self.dataset.train_path: + raise ValueError(""train_path must be specified in the dataset configuration."") + if self.model.encoder_layers <= 0: + raise ValueError(""encoder_layers must be a positive integer."") + if self.training.batch_size <= 0: + raise ValueError(""batch_size must be a positive integer."") + if self.training.update_freq <= 0: + raise ValueError(""update_freq must be a positive integer."") + if self.dataset.preprocess_workers <= 0: + raise ValueError(""preprocess_workers must be a positive integer."") + if self.dataset.stats_workers <= 0: + raise ValueError(""stats_workers must be a positive integer."") + if self.training.lr <= 0: + raise ValueError(""Learning rate must be a positive value."") + if self.training.total_steps <= 0: + raise ValueError(""total_steps must be a positive integer."") + if self.training.keep_last_n_checkpoints <= 0: + raise ValueError(""keep_last_n_checkpoints must be a positive integer."") + if self.training.patience < -1: + raise ValueError(""patience must be -1 or non-negative."") + if self.training.fp16_init_scale <= 0: + raise ValueError(""fp16_init_scale must be a positive value."") + if self.training.fp16_scale_window <= 0: + raise ValueError(""fp16_scale_window must be a positive integer."") + +cs = ConfigStore.instance() +cs.store(name=""pretrain_config"", node=PretrainConfig)","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/pretrain/data_utils.py",".py","610","24","import contextlib +import numpy as np + + +@contextlib.contextmanager +def numpy_seed(seed, *addl_seeds): + """"""Seed NumPy's RNG in a local context. + + This mirrors Uni-Core's utility so that random operations in datasets + are deterministic given the training epoch and sample index. The previous + RNG state is restored when leaving the context. + """""" + if seed is None: + yield + return + if addl_seeds: + seed = int(hash((seed, *addl_seeds)) % 1e6) + state = np.random.get_state() + np.random.seed(seed) + try: + yield + finally: + np.random.set_state(state) +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/config/__init__.py",".py","55","1","from .model_config import MODEL_CONFIG, MODEL_CONFIG_V2","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/config/model_config.py",".py","834","29","MODEL_CONFIG = { + ""weight"": { + ""protein"": ""poc_pre_220816.pt"", + ""molecule_no_h"": ""mol_pre_no_h_220816.pt"", + ""molecule_all_h"": ""mol_pre_all_h_220816.pt"", + ""crystal"": ""mp_all_h_230313.pt"", + ""oled"": ""oled_pre_no_h_230101.pt"", + ""pocket"": ""pocket_pre_220816.pt"", + }, + ""dict"": { + ""protein"": ""poc.dict.txt"", + ""molecule_no_h"": ""mol.dict.txt"", + ""molecule_all_h"": ""mol.dict.txt"", + ""crystal"": ""mp.dict.txt"", + ""oled"": ""oled.dict.txt"", + ""pocket"": ""dict_coarse.txt"", + }, +} + +MODEL_CONFIG_V2 = { + 'weight': { + '84m': 'modelzoo/84M/checkpoint.pt', + '164m': 'modelzoo/164M/checkpoint.pt', + '310m': 'modelzoo/310M/checkpoint.pt', + '570m': 'modelzoo/570M/checkpoint.pt', + '1.1B': 'modelzoo/1.1B/checkpoint.pt', + }, +} +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/data/datareader.py",".py","12083","301","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os +import pathlib + +import numpy as np +import pandas as pd +from rdkit import Chem +from rdkit.Chem import PandasTools +from rdkit.Chem.Scaffolds import MurckoScaffold + +from ..utils import logger + + +class MolDataReader(object): + '''A class to read Mol Data.''' + + def read_data(self, data=None, is_train=True, **params): + # TO DO + # 1. add anomaly detection & outlier removal. + # 2. add support for other file format. + # 3. add support for multi tasks. + + """""" + Reads and preprocesses molecular data from various input formats for model training or prediction. + Parsing target columns + 1. if target_cols is not None, use target_cols as target columns. + 2. if target_cols is None, use all columns with prefix 'target_col_prefix' as target columns. + 3. use given target_cols as target columns placeholder with value -1.0 for predict + + :param data: The input molecular data. Can be a file path (str), a dictionary, or a list of SMILES strings. + :param is_train: (bool) A flag indicating if the operation is for training. Determines data processing steps. + :param params: A dictionary of additional parameters for data processing. + + :return: A dictionary containing processed data and related information for model consumption. + :raises ValueError: If the input data type is not supported or if any SMILES string is invalid (when strict). + """""" + task = params.get('task', None) + target_cols = params.get('target_cols', None) + smiles_col = params.get('smiles_col', 'SMILES') + target_col_prefix = params.get('target_col_prefix', 'TARGET') + anomaly_clean = params.get('anomaly_clean', False) + smi_strict = params.get('smi_strict', False) + split_group_col = params.get('split_group_col', 'scaffold') + + if isinstance(data, str): + # load from file + if data.endswith('.sdf'): + # load sdf file + data = PandasTools.LoadSDF(data) + data = self._convert_numeric_columns(data) + elif data.endswith('.csv'): + data = pd.read_csv(data) + elif data.endswith('.pdb'): + mol = Chem.MolFromPDBFile(data) + data = pd.DataFrame([mol], columns=['pdb_mol']) + else: + raise ValueError('Unknown file type: {}'.format(data)) + elif isinstance(data, dict): + # load from dict + if 'target' in data: + label = np.array(data['target']) + if len(label.shape) == 1 or label.shape[1] == 1: + data[target_col_prefix] = label.reshape(-1) + else: + for i in range(label.shape[1]): + data[target_col_prefix + str(i)] = label[:, i] + + _ = data.pop('target', None) + + if 'atoms' in data and 'coordinates' in data: + if not isinstance(data['atoms'][0], list) and not isinstance(data['atoms'][0], np.ndarray): + data['atoms'] = [data['atoms']] + data['coordinates'] = [data['coordinates']] + if not isinstance(data['atoms'][0][0], str): + pt = Chem.GetPeriodicTable() + data['atoms'] = [ + [pt.GetElementSymbol(int(atom)) for atom in atoms] + for atoms in data['atoms'] + ] + if smiles_col in data and isinstance(data[smiles_col], str): + # if the smiles_col is a single string, convert it to a list + data[smiles_col] = [data[smiles_col]] + if 'residue' in data: + data['residue'] = [data['residue']] # for pocket + + data = pd.DataFrame(data) + + elif isinstance(data, pd.DataFrame): + # load from pandas DataFrame + if 'ROMol' in data.columns: + data = self._convert_numeric_columns(data) + + elif isinstance(data, list) or isinstance(data, np.ndarray): + # load from smiles list + data = pd.DataFrame(data, columns=[smiles_col]) + + elif isinstance(data, pd.Series): + # load from smiles pandas Series + data = data.to_frame(name=smiles_col) + else: + raise ValueError('Unknown data type: {}'.format(type(data))) + + #### parsing target columns + #### 1. if target_cols is not None, use target_cols as target columns. + #### 2. if target_cols is None, use all columns with prefix 'target_col_prefix' as target columns. + #### 3. use given target_cols as target columns placeholder with value -1.0 for predict + if task == 'repr': + # placeholder for repr task + targets = None + target_cols = None + num_classes = None + multiclass_cnt = None + else: + if target_cols is None: + target_cols = [ + item for item in data.columns if item.startswith(target_col_prefix) + ] + elif isinstance(target_cols, str): + target_cols = [target_col.strip() for target_col in target_cols.split(',')] + elif isinstance(target_cols, list): + pass + else: + raise ValueError( + 'Unknown target_cols type: {}'.format(type(target_cols)) + ) + + if is_train: + if anomaly_clean: + data = self.anomaly_clean(data, task, target_cols) + if task == 'multiclass': + multiclass_cnt = int(data[target_cols].max() + 1) + else: + for col in target_cols: + if col not in data.columns or data[col].isnull().any(): + data[col] = -1.0 + + targets = data[target_cols].values.tolist() + num_classes = len(target_cols) + + dd = { + 'raw_data': data, + 'raw_target': targets, + 'num_classes': num_classes, + 'target_cols': target_cols, + 'multiclass_cnt': ( + multiclass_cnt if task == 'multiclass' and is_train else None + ), + } + if smiles_col in data.columns: + mask = data[smiles_col].apply( + lambda smi: self.check_smiles(smi, is_train, smi_strict) + ) + data = data[mask] + dd['smiles'] = data[smiles_col].tolist() + dd['scaffolds'] = data[smiles_col].map(self.smi2scaffold).tolist() + elif 'ROMol' in data.columns: + dd['smiles'] = None + dd['scaffolds'] = data['ROMol'].apply(self.mol2scaffold).tolist() + else: + dd['smiles'] = None + dd['scaffolds'] = None + + if split_group_col in data.columns: + dd['group'] = data[split_group_col].tolist() + elif split_group_col == 'scaffold': + dd['group'] = dd['scaffolds'] + else: + dd['group'] = None + + if 'atoms' in data.columns and 'coordinates' in data.columns: + dd['atoms'] = data['atoms'].tolist() + dd['coordinates'] = data['coordinates'].tolist() + + if 'ROMol' in data.columns: + dd['mols'] = data['ROMol'].tolist() + elif 'pdb_mol' in data.columns: + dd['mols'] = data['pdb_mol'].tolist() + + return dd + + def check_smiles(self, smi, is_train, smi_strict): + """""" + Validates a SMILES string and decides whether it should be included based on training mode and strictness. + + :param smi: (str) The SMILES string to check. + :param is_train: (bool) Indicates if this check is happening during training. + :param smi_strict: (bool) If true, invalid SMILES strings raise an error, otherwise they're logged and skipped. + + :return: (bool) True if the SMILES string is valid, False otherwise. + :raises ValueError: If the SMILES string is invalid and strict mode is on. + """""" + if Chem.MolFromSmiles(smi) is None: + if is_train and not smi_strict: + logger.info(f'Illegal SMILES clean: {smi}') + return False + else: + raise ValueError(f'SMILES rule is illegal: {smi}') + return True + + def smi2scaffold(self, smi): + """""" + Converts a SMILES string to its corresponding scaffold. + + :param smi: (str) The SMILES string to convert. + + :return: (str) The scaffold of the SMILES string, or the original SMILES if conversion fails. + """""" + try: + return MurckoScaffold.MurckoScaffoldSmiles( + smiles=smi, includeChirality=True + ) + except: + return smi + + def mol2scaffold(self, mol): + """""" + Converts an RDKit molecule to its corresponding scaffold. + + :param mol: (RDKit Mol) The molecule to convert. + + :return: (str) The scaffold of the molecule, or the original SMILES if conversion fails. + """""" + if not isinstance(mol, Chem.Mol): + raise ValueError('Input must be an RDKit Mol object') + try: + return MurckoScaffold.MurckoScaffoldSmiles( + mol=mol, includeChirality=True + ) + except: + return Chem.MolToSmiles(mol, includeChirality=True) + + def anomaly_clean(self, data, task, target_cols): + """""" + Performs anomaly cleaning on the data based on the specified task. + + :param data: (DataFrame) The dataset to be cleaned. + :param task: (str) The type of task which determines the cleaning strategy. + :param target_cols: (list) The list of target columns to consider for cleaning. + + :return: (DataFrame) The cleaned dataset. + :raises ValueError: If the provided task is not recognized. + """""" + if task in [ + 'classification', + 'multiclass', + 'multilabel_classification', + 'multilabel_regression', + ]: + return data + if task == 'regression': + return self.anomaly_clean_regression(data, target_cols) + else: + raise ValueError('Unknown task: {}'.format(task)) + + def anomaly_clean_regression(self, data, target_cols): + """""" + Performs anomaly cleaning specifically for regression tasks using a 3-sigma threshold. + + :param data: (DataFrame) The dataset to be cleaned. + :param target_cols: (list) The list of target columns to consider for cleaning. + + :return: (DataFrame) The cleaned dataset after applying the 3-sigma rule. + """""" + sz = data.shape[0] + target_col = target_cols[0] + _mean, _std = data[target_col].mean(), data[target_col].std() + data = data[ + (data[target_col] > _mean - 3 * _std) + & (data[target_col] < _mean + 3 * _std) + ] + logger.info( + 'Anomaly clean with 3 sigma threshold: {} -> {}'.format(sz, data.shape[0]) + ) + return data + + def _convert_numeric_columns(self, df): + """""" + Try to convert all columns in the DataFrame to numeric types, except for the 'ROMol' column. + + :param df: DataFrame to be converted. + :return: DataFrame with numeric columns. + """""" + for col in df.columns: + if col == 'ROMol': + continue + + try: + numeric_series = pd.to_numeric(df[col], errors='coerce') + if numeric_series.isna().sum() / len(df) < 0.1: # Allow up to 10% NaN values + df[col] = numeric_series + logger.debug(f""Column '{col}' converted to numeric type"") + except: + pass + + return df +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/data/dictionary.py",".py","5023","163","# Copyright (c) DP Technology. +# Copyright (c) Facebook, Inc. and its affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. +import logging + +import numpy as np + +logger = logging.getLogger(__name__) # pylint: disable=invalid-name + + +class Dictionary: + """"""A mapping from symbols to consecutive integers"""""" + + def __init__( + self, + *, # begin keyword-only arguments + bos=""[CLS]"", + pad=""[PAD]"", + eos=""[SEP]"", + unk=""[UNK]"", + extra_special_symbols=None, + ): + self.bos_word, self.unk_word, self.pad_word, self.eos_word = bos, unk, pad, eos + self.symbols = [] + self.count = [] + self.indices = {} + self.specials = set() + + # initialize dictionary with special tokens + for token in [bos, unk, pad, eos]: + self.add_symbol(token, is_special=True) + + if extra_special_symbols is not None: + for token in extra_special_symbols: + self.add_symbol(token, is_special=True) + + def __eq__(self, other): + return self.indices == other.indices + + def __getitem__(self, idx): + if idx < len(self.symbols): + return self.symbols[idx] + return self.unk_word + + def __len__(self): + """"""Returns the number of symbols in the dictionary"""""" + return len(self.symbols) + + def __contains__(self, sym): + return sym in self.indices + + def vec_index(self, a): + return np.vectorize(self.index)(a) + + def index(self, sym): + """"""Returns the index of the specified symbol"""""" + assert isinstance(sym, str) + if sym in self.indices: + return self.indices[sym] + return self.indices[self.unk_word] + + def special_index(self): + return [self.index(x) for x in self.specials] + + def add_symbol(self, word, n=1, overwrite=False, is_special=False): + """"""Adds a word to the dictionary"""""" + if is_special: + self.specials.add(word) + if word in self.indices and not overwrite: + idx = self.indices[word] + self.count[idx] = self.count[idx] + n + return idx + else: + idx = len(self.symbols) + self.indices[word] = idx + self.symbols.append(word) + self.count.append(n) + return idx + + def bos(self): + """"""Helper to get index of beginning-of-sentence symbol"""""" + return self.index(self.bos_word) + + def pad(self): + """"""Helper to get index of pad symbol"""""" + return self.index(self.pad_word) + + def eos(self): + """"""Helper to get index of end-of-sentence symbol"""""" + return self.index(self.eos_word) + + def unk(self): + """"""Helper to get index of unk symbol"""""" + return self.index(self.unk_word) + + @classmethod + def load(cls, f): + """"""Loads the dictionary from a text file with the format: + + ``` + + + ... + ``` + """""" + d = cls() + d.add_from_file(f) + return d + + def add_from_file(self, f): + """""" + Loads a pre-existing dictionary from a text file and adds its symbols + to this instance. + """""" + if isinstance(f, str): + try: + with open(f, ""r"", encoding=""utf-8"") as fd: + self.add_from_file(fd) + except FileNotFoundError as fnfe: + raise fnfe + except UnicodeError: + raise Exception( + ""Incorrect encoding detected in {}, please "" + ""rebuild the dataset"".format(f) + ) + return + + lines = f.readlines() + + for line_idx, line in enumerate(lines): + try: + splits = line.rstrip().rsplit("" "", 1) + line = splits[0] + field = splits[1] if len(splits) > 1 else str(len(lines) - line_idx) + if field == ""#overwrite"": + overwrite = True + line, field = line.rsplit("" "", 1) + else: + overwrite = False + count = int(field) + word = line + if word in self and not overwrite: + logger.info( + ""Duplicate word found when loading Dictionary: '{}', index is {}."".format( + word, self.indices[word] + ) + ) + else: + self.add_symbol(word, n=count, overwrite=overwrite) + except ValueError: + raise ValueError( + ""Incorrect dictionary format, expected ' [flags]'"" + ) + + @classmethod + def from_list(cls, symbol_list): + """"""Creates a Dictionary instance from a list of symbols."""""" + d = cls() + for sym in symbol_list: + d.add_symbol(sym) + return d","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/data/__init__.py",".py","64","3","from .datahub import DataHub +from .dictionary import Dictionary +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/data/conformer.py",".py","29425","756","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os +import warnings + +import numpy as np +from rdkit import Chem, RDLogger +from rdkit.Chem import AllChem +from scipy.spatial import distance_matrix + +RDLogger.DisableLog('rdApp.*') +warnings.filterwarnings(action='ignore') +from multiprocessing import Pool + +try: # pragma: no cover - optional dependency + from numba import njit +except ModuleNotFoundError: # pragma: no cover - fallback stub + def njit(*args, **kwargs): + def wrap(fn): + return fn + return wrap +from tqdm import tqdm + +from ..config import MODEL_CONFIG +from ..utils import logger +from ..weights import get_weight_dir, weight_download +from .dictionary import Dictionary + +# https://github.com/snap-stanford/ogb/blob/master/ogb/utils/features.py +# allowable multiple choice node and edge features +allowable_features = { + ""possible_atomic_num_list"": list(range(1, 119)) + [""misc""], + ""possible_chirality_list"": [ + ""CHI_UNSPECIFIED"", + ""CHI_TETRAHEDRAL_CW"", + ""CHI_TETRAHEDRAL_CCW"", + ""CHI_TRIGONALBIPYRAMIDAL"", + ""CHI_OCTAHEDRAL"", + ""CHI_SQUAREPLANAR"", + ""CHI_OTHER"", + ], + ""possible_degree_list"": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ""misc""], + ""possible_formal_charge_list"": [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, ""misc""], + ""possible_numH_list"": [0, 1, 2, 3, 4, 5, 6, 7, 8, ""misc""], + ""possible_number_radical_e_list"": [0, 1, 2, 3, 4, ""misc""], + ""possible_hybridization_list"": [""SP"", ""SP2"", ""SP3"", ""SP3D"", ""SP3D2"", ""misc""], + ""possible_is_aromatic_list"": [False, True], + ""possible_is_in_ring_list"": [False, True], + ""possible_bond_type_list"": [""SINGLE"", ""DOUBLE"", ""TRIPLE"", ""AROMATIC"", ""misc""], + ""possible_bond_stereo_list"": [ + ""STEREONONE"", + ""STEREOZ"", + ""STEREOE"", + ""STEREOCIS"", + ""STEREOTRANS"", + ""STEREOANY"", + ], + ""possible_is_conjugated_list"": [False, True], +} + + +class ConformerGen(object): + ''' + This class designed to generate conformers for molecules represented as SMILES strings using provided parameters and configurations. The `transform` method uses multiprocessing to speed up the conformer generation process. + ''' + + def __init__(self, **params): + """""" + Initializes the neural network model based on the provided model name and parameters. + + :param model_name: (str) The name of the model to initialize. + :param params: Additional parameters for model configuration. + + :return: An instance of the specified neural network model. + :raises ValueError: If the model name is not recognized. + """""" + self._init_features(**params) + + def _init_features(self, **params): + """""" + Initializes the features of the ConformerGen object based on provided parameters. + + :param params: Arbitrary keyword arguments for feature configuration. + These can include the random seed, maximum number of atoms, data type, + generation method, generation mode, and whether to remove hydrogens. + """""" + self.seed = params.get('seed', 42) + self.max_atoms = params.get('max_atoms', 256) + self.data_type = params.get('data_type', 'molecule') + self.method = params.get('method', 'rdkit_random') + self.mode = params.get('mode', 'fast') + self.remove_hs = params.get('remove_hs', False) + # allow using a custom token dictionary to avoid unnecessary downloads + dict_path = params.get('pretrained_dict_path', None) + if dict_path is not None: + # load dictionary from user-provided path + self.dictionary = Dictionary.load(dict_path) + else: + if self.data_type == 'molecule': + name = ""no_h"" if self.remove_hs else ""all_h"" + name = self.data_type + '_' + name + self.dict_name = MODEL_CONFIG['dict'][name] + else: + self.dict_name = MODEL_CONFIG['dict'][self.data_type] + weight_dir = get_weight_dir() + if not os.path.exists(os.path.join(weight_dir, self.dict_name)): + weight_download(self.dict_name, weight_dir) + self.dictionary = Dictionary.load( + os.path.join(weight_dir, self.dict_name) + ) + self.dictionary.add_symbol(""[MASK]"", is_special=True) + if os.name == 'posix': + self.multi_process = params.get('multi_process', True) + else: + self.multi_process = params.get('multi_process', False) + if self.multi_process: + logger.warning( + 'Please use ""if __name__ == ""__main__"":"" to wrap the main function when using multi_process on Windows.' + ) + + def single_process(self, smiles): + """""" + Processes a single SMILES string to generate conformers using the specified method. + + :param smiles: (str) The SMILES string representing the molecule. + :return: A unimolecular data representation (dictionary) of the molecule. + :raises ValueError: If the conformer generation method is unrecognized. + """""" + if self.method == 'rdkit_random': + atoms, coordinates, mol = inner_smi2coords( + smiles, seed=self.seed, mode=self.mode, remove_hs=self.remove_hs + ) + feat = coords2unimol( + atoms, + coordinates, + self.dictionary, + self.max_atoms, + remove_hs=self.remove_hs, + data_type=self.data_type, + ) + return feat, mol + else: + raise ValueError( + 'Unknown conformer generation method: {}'.format(self.method) + ) + + def transform_raw(self, atoms_list, coordinates_list): + + inputs = [] + for atoms, coordinates in zip(atoms_list, coordinates_list): + inputs.append( + coords2unimol( + atoms, + coordinates, + self.dictionary, + self.max_atoms, + remove_hs=self.remove_hs, + data_type=self.data_type, + ) + ) + return inputs + + def transform_mols(self, mols_list): + inputs = [] + for mol in mols_list: + atoms = np.array([atom.GetSymbol() for atom in mol.GetAtoms()]) + coordinates = mol.GetConformer().GetPositions().astype(np.float32) + inputs.append( + coords2unimol( + atoms, + coordinates, + self.dictionary, + self.max_atoms, + remove_hs=self.remove_hs, + data_type=self.data_type, + ) + ) + return inputs + + def transform(self, smiles_list): + logger.info('Start generating conformers...') + if self.multi_process: + pool = Pool(processes=min(8, os.cpu_count())) + results = [ + item for item in tqdm(pool.imap(self.single_process, smiles_list)) + ] + pool.close() + else: + results = [self.single_process(smiles) for smiles in tqdm(smiles_list)] + + inputs, mols = zip(*results) + inputs = list(inputs) + mols = list(mols) + + failed_conf = [(item['src_coord'] == 0.0).all() for item in inputs] + logger.info( + 'Succeeded in generating conformers for {:.2f}% of molecules.'.format( + (1 - np.mean(failed_conf)) * 100 + ) + ) + failed_conf_indices = [ + index for index, value in enumerate(failed_conf) if value + ] + if len(failed_conf_indices) > 0: + logger.info('Failed conformers indices: {}'.format(failed_conf_indices)) + logger.debug( + 'Failed conformers SMILES: {}'.format( + [smiles_list[index] for index in failed_conf_indices] + ) + ) + + failed_conf_3d = [(item['src_coord'][:, 2] == 0.0).all() for item in inputs] + logger.info( + 'Succeeded in generating 3d conformers for {:.2f}% of molecules.'.format( + (1 - np.mean(failed_conf_3d)) * 100 + ) + ) + failed_conf_3d_indices = [ + index for index, value in enumerate(failed_conf_3d) if value + ] + if len(failed_conf_3d_indices) > 0: + logger.info( + 'Failed 3d conformers indices: {}'.format(failed_conf_3d_indices) + ) + logger.debug( + 'Failed 3d conformers SMILES: {}'.format( + [smiles_list[index] for index in failed_conf_3d_indices] + ) + ) + return inputs, mols + + +def inner_smi2coords(smi, seed=42, mode='fast', remove_hs=True, return_mol=False): + ''' + This function is responsible for converting a SMILES (Simplified Molecular Input Line Entry System) string into 3D coordinates for each atom in the molecule. It also allows for the generation of 2D coordinates if 3D conformation generation fails, and optionally removes hydrogen atoms and their coordinates from the resulting data. + + :param smi: (str) The SMILES representation of the molecule. + :param seed: (int, optional) The random seed for conformation generation. Defaults to 42. + :param mode: (str, optional) The mode of conformation generation, 'fast' for quick generation, 'heavy' for more attempts. Defaults to 'fast'. + :param remove_hs: (bool, optional) Whether to remove hydrogen atoms from the final coordinates. Defaults to True. + + :return: A tuple containing the list of atom symbols and their corresponding 3D coordinates. + :raises AssertionError: If no atoms are present in the molecule or if the coordinates do not align with the atom count. + ''' + mol = Chem.MolFromSmiles(smi) + mol = AllChem.AddHs(mol) + atoms = [atom.GetSymbol() for atom in mol.GetAtoms()] + assert len(atoms) > 0, 'No atoms in molecule: {}'.format(smi) + try: + # will random generate conformer with seed equal to -1. else fixed random seed. + res = AllChem.EmbedMolecule(mol, randomSeed=seed) + if res == 0: + try: + # some conformer can not use MMFF optimize + AllChem.MMFFOptimizeMolecule(mol) + coordinates = mol.GetConformer().GetPositions().astype(np.float32) + except: + coordinates = mol.GetConformer().GetPositions().astype(np.float32) + ## for fast test... ignore this ### + elif res == -1 and mode == 'heavy': + AllChem.EmbedMolecule(mol, maxAttempts=5000, randomSeed=seed) + try: + # some conformer can not use MMFF optimize + AllChem.MMFFOptimizeMolecule(mol) + coordinates = mol.GetConformer().GetPositions().astype(np.float32) + except: + AllChem.Compute2DCoords(mol) + coordinates_2d = mol.GetConformer().GetPositions().astype(np.float32) + coordinates = coordinates_2d + else: + AllChem.Compute2DCoords(mol) + coordinates_2d = mol.GetConformer().GetPositions().astype(np.float32) + coordinates = coordinates_2d + except: + print(""Failed to generate conformer, replace with zeros."") + coordinates = np.zeros((len(atoms), 3)) + + if return_mol: + return mol # for unimolv2 + + assert len(atoms) == len( + coordinates + ), ""coordinates shape is not align with {}"".format(smi) + if remove_hs: + idx = [i for i, atom in enumerate(atoms) if atom != 'H'] + atoms_no_h = [atom for atom in atoms if atom != 'H'] + coordinates_no_h = coordinates[idx] + assert len(atoms_no_h) == len( + coordinates_no_h + ), ""coordinates shape is not align with {}"".format(smi) + return atoms_no_h, coordinates_no_h, mol + else: + return atoms, coordinates, mol + + +def inner_coords(atoms, coordinates, remove_hs=True): + """""" + Processes a list of atoms and their corresponding coordinates to remove hydrogen atoms if specified. + This function takes a list of atom symbols and their corresponding coordinates and optionally removes hydrogen atoms from the output. It includes assertions to ensure the integrity of the data and uses numpy for efficient processing of the coordinates. + + :param atoms: (list) A list of atom symbols (e.g., ['C', 'H', 'O']). + :param coordinates: (list of tuples or list of lists) Coordinates corresponding to each atom in the `atoms` list. + :param remove_hs: (bool, optional) A flag to indicate whether hydrogen atoms should be removed from the output. + Defaults to True. + + :return: A tuple containing two elements; the filtered list of atom symbols and their corresponding coordinates. + If `remove_hs` is False, the original lists are returned. + + :raises AssertionError: If the length of `atoms` list does not match the length of `coordinates` list. + """""" + assert len(atoms) == len(coordinates), ""coordinates shape is not align atoms"" + coordinates = np.array(coordinates).astype(np.float32) + if remove_hs: + idx = [i for i, atom in enumerate(atoms) if atom != 'H'] + atoms_no_h = [atom for atom in atoms if atom != 'H'] + coordinates_no_h = coordinates[idx] + assert len(atoms_no_h) == len( + coordinates_no_h + ), ""coordinates shape is not align with atoms"" + return atoms_no_h, coordinates_no_h + else: + return atoms, coordinates + + +def coords2unimol( + atoms, coordinates, dictionary, max_atoms=256, remove_hs=True, data_type='molecule', **params +): + """""" + Converts atom symbols and coordinates into a unified molecular representation. + + :param atoms: (list) List of atom symbols. + :param coordinates: (ndarray) Array of atomic coordinates. + :param dictionary: (Dictionary) An object that maps atom symbols to unique integers. + :param max_atoms: (int) The maximum number of atoms to consider for the molecule. + :param remove_hs: (bool) Whether to remove hydrogen atoms from the representation. + :param params: Additional parameters. + + :return: A dictionary containing the molecular representation with tokens, distances, coordinates, and edge types. + """""" + atoms, coordinates = inner_coords(atoms, coordinates, remove_hs=remove_hs) + atoms = np.array(atoms) + coordinates = np.array(coordinates).astype(np.float32) + # cropping atoms and coordinates + if len(atoms) > max_atoms: + idx = np.random.choice(len(atoms), max_atoms, replace=False) + atoms = atoms[idx] + coordinates = coordinates[idx] + # tokens padding + if data_type == 'pocket': + src_tokens_mid = [dictionary.index(atom[0]) for atom in atoms] + else: + src_tokens_mid = [dictionary.index(atom) for atom in atoms] + + src_tokens = np.array( + [dictionary.bos()] + + src_tokens_mid + + [dictionary.eos()] + ) + src_distance = np.zeros((len(src_tokens), len(src_tokens))) + # coordinates normalize & padding + src_coord = coordinates - coordinates.mean(axis=0) + src_coord = np.concatenate([np.zeros((1, 3)), src_coord, np.zeros((1, 3))], axis=0) + # distance matrix + src_distance = distance_matrix(src_coord, src_coord) + # edge type + src_edge_type = src_tokens.reshape(-1, 1) * len(dictionary) + src_tokens.reshape( + 1, -1 + ) + + return { + 'src_tokens': src_tokens.astype(int), + 'src_distance': src_distance.astype(np.float32), + 'src_coord': src_coord.astype(np.float32), + 'src_edge_type': src_edge_type.astype(int), + } + + +class UniMolV2Feature(object): + ''' + This class is responsible for generating features for molecules represented as SMILES strings. It uses the ConformerGen class to generate conformers for the molecules and converts the resulting atom symbols and coordinates into a unified molecular representation. + ''' + + def __init__(self, **params): + """""" + Initializes the neural network model based on the provided model name and parameters. + + :param model_name: (str) The name of the model to initialize. + :param params: Additional parameters for model configuration. + + :return: An instance of the specified neural network model. + :raises ValueError: If the model name is not recognized. + """""" + self._init_features(**params) + + def _init_features(self, **params): + """""" + Initializes the features of the UniMolV2Feature object based on provided parameters. + + :param params: Arbitrary keyword arguments for feature configuration. + These can include the random seed, maximum number of atoms, data type, + generation method, generation mode, and whether to remove hydrogens. + """""" + self.seed = params.get('seed', 42) + self.max_atoms = params.get('max_atoms', 128) + self.data_type = params.get('data_type', 'molecule') + self.method = params.get('method', 'rdkit_random') + self.mode = params.get('mode', 'fast') + self.remove_hs = params.get('remove_hs', True) + if os.name == 'posix': + self.multi_process = params.get('multi_process', True) + else: + self.multi_process = params.get('multi_process', False) + if self.multi_process: + logger.warning( + 'Please use ""if __name__ == ""__main__"":"" to wrap the main function when using multi_process on Windows.' + ) + + def single_process(self, smiles): + """""" + Processes a single SMILES string to generate conformers using the specified method. + + :param smiles: (str) The SMILES string representing the molecule. + :return: A unimolecular data representation (dictionary) of the molecule. + :raises ValueError: If the conformer generation method is unrecognized. + """""" + if self.method == 'rdkit_random': + mol = inner_smi2coords( + smiles, + seed=self.seed, + mode=self.mode, + remove_hs=self.remove_hs, + return_mol=True, + ) + feat = mol2unimolv2(mol, self.max_atoms, remove_hs=self.remove_hs) + return feat, mol + else: + raise ValueError( + 'Unknown conformer generation method: {}'.format(self.method) + ) + + def transform_raw(self, atoms_list, coordinates_list): + + inputs = [] + for atoms, coordinates in zip(atoms_list, coordinates_list): + mol = create_mol_from_atoms_and_coords(atoms, coordinates) + inputs.append(mol2unimolv2(mol, self.max_atoms, remove_hs=self.remove_hs)) + return inputs + + def transform_mols(self, mols_list): + inputs = [] + for mol in mols_list: + inputs.append(mol2unimolv2(mol, self.max_atoms, remove_hs=self.remove_hs)) + return inputs + + def transform(self, smiles_list): + logger.info('Start generating conformers...') + if self.multi_process: + pool = Pool(processes=min(8, os.cpu_count())) + results = [ + item for item in tqdm(pool.imap(self.single_process, smiles_list)) + ] + pool.close() + else: + results = [self.single_process(smiles) for smiles in tqdm(smiles_list)] + + inputs, mols = zip(*results) + inputs = list(inputs) + mols = list(mols) + + failed_conf = [(item['src_coord'] == 0.0).all() for item in inputs] + logger.info( + 'Succeeded in generating conformers for {:.2f}% of molecules.'.format( + (1 - np.mean(failed_conf)) * 100 + ) + ) + failed_conf_indices = [ + index for index, value in enumerate(failed_conf) if value + ] + if len(failed_conf_indices) > 0: + logger.info('Failed conformers indices: {}'.format(failed_conf_indices)) + logger.debug( + 'Failed conformers SMILES: {}'.format( + [smiles_list[index] for index in failed_conf_indices] + ) + ) + + failed_conf_3d = [(item['src_coord'][:, 2] == 0.0).all() for item in inputs] + logger.info( + 'Succeeded in generating 3d conformers for {:.2f}% of molecules.'.format( + (1 - np.mean(failed_conf_3d)) * 100 + ) + ) + failed_conf_3d_indices = [ + index for index, value in enumerate(failed_conf_3d) if value + ] + if len(failed_conf_3d_indices) > 0: + logger.info( + 'Failed 3d conformers indices: {}'.format(failed_conf_3d_indices) + ) + logger.debug( + 'Failed 3d conformers SMILES: {}'.format( + [smiles_list[index] for index in failed_conf_3d_indices] + ) + ) + + return inputs, mols + + +def create_mol_from_atoms_and_coords(atoms, coordinates): + """""" + Creates an RDKit molecule object from a list of atom symbols and their corresponding coordinates. + + :param atoms: (list) Atom symbols for the molecule. + :param coordinates: (list) Atomic coordinates for the molecule. + :return: RDKit molecule object. + """""" + mol = Chem.RWMol() + atom_indices = [] + + for atom in atoms: + atom_idx = mol.AddAtom(Chem.Atom(atom)) + atom_indices.append(atom_idx) + + conf = Chem.Conformer(len(atoms)) + for i, coord in enumerate(coordinates): + conf.SetAtomPosition(i, coord) + + mol.AddConformer(conf) + Chem.SanitizeMol(mol) + return mol + + +def mol2unimolv2(mol, max_atoms=128, remove_hs=True, **params): + """""" + Converts atom symbols and coordinates into a unified molecular representation. + + :param mol: (rdkit.Chem.Mol) The molecule object containing atom symbols and coordinates. + :param max_atoms: (int) The maximum number of atoms to consider for the molecule. + :param remove_hs: (bool) Whether to remove hydrogen atoms from the representation. This must be True for UniMolV2. + :param params: Additional parameters. + + :return: A batched data containing the molecular representation. + """""" + + mol = AllChem.RemoveAllHs(mol) + atoms = np.array([atom.GetSymbol() for atom in mol.GetAtoms()]) + coordinates = mol.GetConformer().GetPositions().astype(np.float32) + + # cropping atoms and coordinates + if len(atoms) > max_atoms: + mask = np.zeros(len(atoms), dtype=bool) + mask[:max_atoms] = True + np.random.shuffle(mask) # shuffle the mask + atoms = atoms[mask] + coordinates = coordinates[mask] + else: + mask = np.ones(len(atoms), dtype=bool) + # tokens padding + src_tokens = [AllChem.GetPeriodicTable().GetAtomicNumber(item) for item in atoms] + src_coord = coordinates + # + node_attr, edge_index, edge_attr = get_graph(mol) + feat = get_graph_features(edge_attr, edge_index, node_attr, drop_feat=0, mask=mask) + feat['src_tokens'] = src_tokens + feat['src_coord'] = src_coord + return feat + + +def safe_index(l, e): + """""" + Return index of element e in list l. If e is not present, return the last index + """""" + try: + return l.index(e) + except: + return len(l) - 1 + + +def atom_to_feature_vector(atom): + """""" + Converts rdkit atom object to feature list of indices + :param mol: rdkit atom object + :return: list + """""" + atom_feature = [ + safe_index(allowable_features[""possible_atomic_num_list""], atom.GetAtomicNum()), + allowable_features[""possible_chirality_list""].index(str(atom.GetChiralTag())), + safe_index(allowable_features[""possible_degree_list""], atom.GetTotalDegree()), + safe_index( + allowable_features[""possible_formal_charge_list""], atom.GetFormalCharge() + ), + safe_index(allowable_features[""possible_numH_list""], atom.GetTotalNumHs()), + safe_index( + allowable_features[""possible_number_radical_e_list""], + atom.GetNumRadicalElectrons(), + ), + safe_index( + allowable_features[""possible_hybridization_list""], + str(atom.GetHybridization()), + ), + allowable_features[""possible_is_aromatic_list""].index(atom.GetIsAromatic()), + allowable_features[""possible_is_in_ring_list""].index(atom.IsInRing()), + ] + return atom_feature + + +def bond_to_feature_vector(bond): + """""" + Converts rdkit bond object to feature list of indices + :param mol: rdkit bond object + :return: list + """""" + bond_feature = [ + safe_index( + allowable_features[""possible_bond_type_list""], str(bond.GetBondType()) + ), + allowable_features[""possible_bond_stereo_list""].index(str(bond.GetStereo())), + allowable_features[""possible_is_conjugated_list""].index(bond.GetIsConjugated()), + ] + return bond_feature + + +def get_graph(mol): + """""" + Converts SMILES string to graph Data object + :input: SMILES string (str) + :return: graph object + """""" + atom_features_list = [] + for atom in mol.GetAtoms(): + atom_features_list.append(atom_to_feature_vector(atom)) + x = np.array(atom_features_list, dtype=np.int32) + # bonds + num_bond_features = 3 # bond type, bond stereo, is_conjugated + if len(mol.GetBonds()) > 0: # mol has bonds + edges_list = [] + edge_features_list = [] + for bond in mol.GetBonds(): + i = bond.GetBeginAtomIdx() + j = bond.GetEndAtomIdx() + edge_feature = bond_to_feature_vector(bond) + # add edges in both directions + edges_list.append((i, j)) + edge_features_list.append(edge_feature) + edges_list.append((j, i)) + edge_features_list.append(edge_feature) + # data.edge_index: Graph connectivity in COO format with shape [2, num_edges] + edge_index = np.array(edges_list, dtype=np.int32).T + # data.edge_attr: Edge feature matrix with shape [num_edges, num_edge_features] + edge_attr = np.array(edge_features_list, dtype=np.int32) + + else: # mol has no bonds + edge_index = np.empty((2, 0), dtype=np.int32) + edge_attr = np.empty((0, num_bond_features), dtype=np.int32) + return x, edge_index, edge_attr + + +def get_graph_features(edge_attr, edge_index, node_attr, drop_feat, mask): + # atom_feat_sizes = [128] + [16 for _ in range(8)] + atom_feat_sizes = [16 for _ in range(8)] + edge_feat_sizes = [16, 16, 16] + edge_attr, edge_index, x = edge_attr, edge_index, node_attr + N = x.shape[0] + + # atom feature here + atom_feat = convert_to_single_emb(x[:, 1:], atom_feat_sizes) + + # node adj matrix [N, N] bool + adj = np.zeros([N, N], dtype=np.int32) + adj[edge_index[0, :], edge_index[1, :]] = 1 + degree = adj.sum(axis=-1) + + # edge feature here + if len(edge_attr.shape) == 1: + edge_attr = edge_attr[:, None] + edge_feat = np.zeros([N, N, edge_attr.shape[-1]], dtype=np.int32) + edge_feat[edge_index[0, :], edge_index[1, :]] = ( + convert_to_single_emb(edge_attr, edge_feat_sizes) + 1 + ) + shortest_path_result = floyd_warshall(adj) + # max distance is 509 + if drop_feat: + atom_feat[...] = 1 + edge_feat[...] = 1 + degree[...] = 1 + shortest_path_result[...] = 511 + else: + atom_feat = atom_feat + 2 + edge_feat = edge_feat + 2 + degree = degree + 2 + shortest_path_result = shortest_path_result + 1 + + # combine, plus 1 for padding + feat = {} + feat[""atom_feat""] = atom_feat[mask] + feat[""atom_mask""] = np.ones(N, dtype=np.int64)[mask] + feat[""edge_feat""] = edge_feat[mask][:, mask] + feat[""shortest_path""] = shortest_path_result[mask][:, mask] + feat[""degree""] = degree.reshape(-1)[mask] + # pair-type + atoms = atom_feat[..., 0] + pair_type = np.concatenate( + [ + np.expand_dims(atoms, axis=(1, 2)).repeat(N, axis=1), + np.expand_dims(atoms, axis=(0, 2)).repeat(N, axis=0), + ], + axis=-1, + ) + pair_type = pair_type[mask][:, mask] + feat[""pair_type""] = convert_to_single_emb(pair_type, [128, 128]) + feat[""attn_bias""] = np.zeros((mask.sum() + 1, mask.sum() + 1), dtype=np.float32) + return feat + + +def convert_to_single_emb(x, sizes): + assert x.shape[-1] == len(sizes) + offset = 1 + for i in range(len(sizes)): + assert (x[..., i] < sizes[i]).all() + x[..., i] = x[..., i] + offset + offset += sizes[i] + return x + + +@njit +def floyd_warshall(M): + (nrows, ncols) = M.shape + assert nrows == ncols + n = nrows + # set unreachable nodes distance to 510 + for i in range(n): + for j in range(n): + if M[i, j] == 0: + M[i, j] = 510 + + for i in range(n): + M[i, i] = 0 + + # floyed algo + for k in range(n): + for i in range(n): + for j in range(n): + cost_ikkj = M[i, k] + M[k, j] + if M[i, j] > cost_ikkj: + M[i, j] = cost_ikkj + + for i in range(n): + for j in range(n): + if M[i, j] >= 510: + M[i, j] = 510 + return M +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/data/split.py",".py","4514","112","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import numpy as np +from sklearn.model_selection import GroupKFold, KFold, StratifiedKFold + +from ..utils import logger + + +class Splitter(object): + """""" + The Splitter class is responsible for splitting a dataset into train and test sets + based on the specified method. + """""" + + def __init__(self, method='random', kfold=5, seed=42, **params): + """""" + Initializes the Splitter with a specified split method and random seed. + + :param split_method: (str) The method for splitting the dataset, in the format 'Nfold_method'. + Defaults to '5fold_random'. + :param seed: (int) Random seed for reproducibility in random splitting. Defaults to 42. + """""" + self.method = method + self.n_splits = kfold + self.seed = seed + self.splitter = self._init_split() + + def _init_split(self): + """""" + Initializes the actual splitter object based on the specified method. + + :return: The initialized splitter object. + :raises ValueError: If an unknown splitting method is specified. + """""" + if self.n_splits == 1: + return None + if self.method == 'random': + splitter = KFold( + n_splits=self.n_splits, shuffle=True, random_state=self.seed + ) + elif self.method == 'scaffold' or self.method == 'group': + splitter = GroupKFold(n_splits=self.n_splits) + elif self.method == 'stratified': + splitter = StratifiedKFold( + n_splits=self.n_splits, shuffle=True, random_state=self.seed + ) + elif self.method == 'select': + splitter = GroupKFold(n_splits=self.n_splits) + else: + raise ValueError( + 'Unknown splitter method: {}fold - {}'.format( + self.n_splits, self.method + ) + ) + + return splitter + + def split(self, smiles, target=None, group=None, scaffolds=None, **params): + """""" + Splits the dataset into train and test sets based on the initialized method. + + :param data: The dataset to be split. + :param target: (optional) Target labels for stratified splitting. Defaults to None. + :param group: (optional) Group labels for group-based splitting. Defaults to None. + + :return: An iterator yielding train and test set indices for each fold. + :raises ValueError: If the splitter method does not support the provided parameters. + """""" + if self.n_splits == 1: + logger.warning( + 'Only one fold is used for training, no splitting is performed.' + ) + return [(np.arange(len(smiles)), ())] + if smiles is None and 'atoms' in params: + smiles = params['atoms'] + logger.warning('Atoms are used as SMILES for splitting.') + elif smiles is None and 'mols' in params: + smiles = params['mols'] + logger.warning('Mols are used as SMILES for splitting.') + if self.method in ['random']: + self.skf = self.splitter.split(smiles) + elif self.method in ['scaffold']: + self.skf = self.splitter.split(smiles, target, scaffolds) + elif self.method in ['group']: + self.skf = self.splitter.split(smiles, target, group) + elif self.method in ['stratified']: + self.skf = self.splitter.split(smiles, group) + elif self.method in ['select']: + unique_groups = np.unique(group) + if len(unique_groups) == self.n_splits: + split_folds = [] + for unique_group in unique_groups: + train_idx = np.where(group != unique_group)[0] + test_idx = np.where(group == unique_group)[0] + split_folds.append((train_idx, test_idx)) + self.split_folds = split_folds + return self.split_folds + else: + logger.error( + 'The number of unique groups is not equal to the number of splits.' + ) + exit(1) + else: + logger.error('Unknown splitter method: {}'.format(self.method)) + exit(1) + self.split_folds = list(self.skf) + return self.split_folds +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/data/datahub.py",".py","9071","205","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os +import numpy as np +import pandas as pd +from rdkit.Chem import PandasTools + +from ..utils import logger +from .conformer import ConformerGen, UniMolV2Feature +from .datareader import MolDataReader +from .datascaler import TargetScaler +from .split import Splitter + + +class DataHub(object): + """""" + The DataHub class is responsible for storing and preprocessing data for machine learning tasks. + It initializes with configuration options to handle different types of tasks such as regression, + classification, and others. It also supports data scaling and handling molecular data. + """""" + + def __init__(self, data=None, is_train=True, save_path=None, **params): + """""" + Initializes the DataHub instance with data and configuration for the ML task. + + :param data: Initial dataset to be processed. + :param is_train: (bool) Indicates if the DataHub is being used for training. + :param save_path: (str) Path to save any necessary files, like scalers. + :param params: Additional parameters for data preprocessing and model configuration. + """""" + self.raw_data = data + self.is_train = is_train + self.save_path = save_path + self.task = params.get('task', None) + # self.target_cols = params.get('target_cols', None) + self.multiclass_cnt = params.get('multiclass_cnt', None) + self.ss_method = params.get('target_normalize', 'none') + self.conf_cache_level = params.get('conf_cache_level', 1) + self._init_data(**params) + self._init_split(**params) + + def _init_data(self, **params): + """""" + Initializes and preprocesses the data based on the task and parameters provided. + + This method handles reading raw data, scaling targets, and transforming data for use with + molecular inputs. It tailors the preprocessing steps based on the task type, such as regression + or classification. + + :param params: Additional parameters for data processing. + :raises ValueError: If the task type is unknown. + """""" + self.data = MolDataReader().read_data(self.raw_data, self.is_train, **params) + self.data['target_scaler'] = TargetScaler( + self.ss_method, self.task, self.save_path + ) + if self.task == 'regression': + target = np.array(self.data['raw_target']).reshape(-1, 1).astype(np.float32) + if self.is_train: + self.data['target_scaler'].fit(target, self.save_path) + self.data['target'] = self.data['target_scaler'].transform(target) + else: + self.data['target'] = target + elif self.task == 'classification': + target = np.array(self.data['raw_target']).reshape(-1, 1).astype(np.int32) + self.data['target'] = target + elif self.task == 'multiclass': + target = np.array(self.data['raw_target']).reshape(-1, 1).astype(np.int32) + self.data['target'] = target + if not self.is_train: + self.data['multiclass_cnt'] = self.multiclass_cnt + elif self.task == 'multilabel_regression': + target = ( + np.array(self.data['raw_target']) + .reshape(-1, self.data['num_classes']) + .astype(np.float32) + ) + if self.is_train: + self.data['target_scaler'].fit(target, self.save_path) + self.data['target'] = self.data['target_scaler'].transform(target) + else: + self.data['target'] = target + elif self.task == 'multilabel_classification': + target = ( + np.array(self.data['raw_target']) + .reshape(-1, self.data['num_classes']) + .astype(np.int32) + ) + self.data['target'] = target + elif self.task == 'repr': + self.data['target'] = self.data['raw_target'] + else: + raise ValueError('Unknown task: {}'.format(self.task)) + + if params.get('model_name', None) == 'unimolv1': + if 'mols' in self.data: + no_h_list = ConformerGen(**params).transform_mols(self.data['mols']) + mols = None + elif 'atoms' in self.data and 'coordinates' in self.data: + no_h_list = ConformerGen(**params).transform_raw( + self.data['atoms'], self.data['coordinates'] + ) + mols = None + else: + smiles_list = self.data[""smiles""] + no_h_list, mols = ConformerGen(**params).transform(smiles_list) + elif params.get('model_name', None) == 'unimolv2': + if 'mols' in self.data: + no_h_list = UniMolV2Feature(**params).transform_mols(self.data['mols']) + mols = None + elif 'atoms' in self.data and 'coordinates' in self.data: + no_h_list = UniMolV2Feature(**params).transform_raw( + self.data['atoms'], self.data['coordinates'] + ) + mols = None + else: + smiles_list = self.data[""smiles""] + no_h_list, mols = UniMolV2Feature(**params).transform(smiles_list) + + self.data['unimol_input'] = no_h_list + + if mols is not None: + self.save_mol2sdf(self.data['raw_data'], mols, params) + + def _init_split(self, **params): + + self.split_method = params.get('split_method', '5fold_random') + kfold, method = ( + int(self.split_method.split('fold')[0]), + self.split_method.split('_')[-1], + ) # Nfold_xxxx + self.kfold = params.get('kfold', kfold) + self.method = params.get('split', method) + self.split_seed = params.get('split_seed', 42) + self.data['kfold'] = self.kfold + if not self.is_train: + return + self.splitter = Splitter(self.method, self.kfold, seed=self.split_seed) + split_nfolds = self.splitter.split(**self.data) + if self.kfold == 1: + logger.info(f""Kfold is 1, all data is used for training."") + else: + logger.info(f""Split method: {self.method}, fold: {self.kfold}"") + nfolds = np.zeros(len(split_nfolds[0][0]) + len(split_nfolds[0][1]), dtype=int) + for enu, (tr_idx, te_idx) in enumerate(split_nfolds): + nfolds[te_idx] = enu + self.data['split_nfolds'] = split_nfolds + return split_nfolds + + def save_mol2sdf(self, data, mols, params): + """""" + Save the conformers to a SDF file. + + :param data: DataFrame containing the raw data. + :param mols: List of RDKit molecule objects. + """""" + if isinstance(self.raw_data, str): + base_name = os.path.splitext(os.path.basename(self.raw_data))[0] + elif isinstance(self.raw_data, list) or isinstance(self.raw_data, np.ndarray) or isinstance(self.raw_data, pd.Series): + # If the raw_data is a list of smiles, we can use a default name. + base_name = 'unimol_conformers' + elif isinstance(self.raw_data, pd.DataFrame) or isinstance(self.raw_data, dict): + if self.is_train: + base_name = 'unimol_conformers_train' + else: + base_name = 'unimol_conformers' + else: + logger.warning('Warning: raw_data is not a path or list of smiles, cannot save sdf.') + return + if params.get('sdf_save_path') is None: + if self.save_path is not None: + params['sdf_save_path'] = self.save_path + else: + return + save_path = os.path.join(params.get('sdf_save_path'), f""{base_name}.sdf"") + if self.conf_cache_level == 0: + logger.warning(f""conf_cache_level is 0, do not save conformers."") + return + elif self.conf_cache_level == 1 and os.path.exists(save_path): + logger.warning(f""conf_cache_level is 1, but {save_path} exists, so do not save conformers."") + return + elif self.conf_cache_level == 2 or not os.path.exists(save_path): + logger.info(f""conf_cache_level is {self.conf_cache_level}, saving conformers to {save_path}."") + else: + logger.warning(f""Unknown conf_cache_level: {self.conf_cache_level}, do not saving conformers."") + return + sdf_result = data.copy() + sdf_result['ROMol'] = mols + os.makedirs(os.path.dirname(save_path), exist_ok=True) + try: + PandasTools.WriteSDF( + sdf_result, + save_path, + properties=list(sdf_result.columns), + idName='RowID', + ) + logger.info(f""Successfully saved sdf file to {save_path}"") + except Exception as e: + logger.warning(f""Failed to write sdf file: {e}"") + pass +","Python" +"QSAR","deepmodeling/unimol_tools","unimol_tools/data/datascaler.py",".py","8026","219","# Copyright (c) DP Technology. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import absolute_import, division, print_function + +import os + +import joblib +import numpy as np +from scipy.stats import kurtosis, skew +from sklearn.preprocessing import ( + FunctionTransformer, + MaxAbsScaler, + MinMaxScaler, + Normalizer, + PowerTransformer, + QuantileTransformer, + RobustScaler, + StandardScaler, +) + +from ..utils import logger + + +class TargetScaler(object): + ''' + A class to scale the target. + ''' + + def __init__(self, ss_method, task, load_dir=None): + """""" + Initializes the TargetScaler object for scaling target values. + + :param ss_method: (str) The scaling method to be used. + :param task: (str) The type of machine learning task (e.g., 'classification', 'regression'). + :param load_dir: (str, optional) Directory from which to load an existing scaler. + """""" + self.ss_method = ss_method + self.task = task + if load_dir and os.path.exists(os.path.join(load_dir, 'target_scaler.ss')): + self.scaler = joblib.load(os.path.join(load_dir, 'target_scaler.ss')) + else: + self.scaler = None + + def transform(self, target): + """""" + Transforms the target values using the appropriate scaling method. + + :param target: (array-like) The target values to be transformed. + + :return: (array-like) The transformed target values. + """""" + if self.task in ['classification', 'multiclass', 'multilabel_classification']: + return target + elif self.ss_method == 'none': + return target + elif self.task == 'regression': + return self.scaler.transform(target) + elif self.task == 'multilabel_regression': + assert isinstance(self.scaler, list) and len(self.scaler) == target.shape[1] + target = np.ma.masked_invalid(target) # mask NaN value + new_target = np.zeros_like(target) + for i in range(target.shape[1]): + new_target[:, i] = ( + self.scaler[i] + .transform(target[:, i : i + 1]) + .reshape( + -1, + ) + ) + return new_target + else: + return target + + def fit(self, target, dump_dir): + """""" + Fits the scaler to the target values and optionally saves the scaler to disk. + + :param target: (array-like) The target values to fit the scaler. + :param dump_dir: (str) Directory where the fitted scaler will be saved. + """""" + if self.task in ['classification', 'multiclass', 'multilabel_classification']: + return + elif self.ss_method == 'none': + return + elif self.ss_method == 'auto': + if self.task == 'regression': + if self.is_skewed(target): + self.scaler = FunctionTransformer( + func=np.log1p, inverse_func=np.expm1 + ) + logger.info('Auto select robust transformer.') + else: + self.scaler = StandardScaler() + self.scaler.fit(target) + elif self.task == 'multilabel_regression': + self.scaler = [] + target = np.ma.masked_invalid(target) # mask NaN value + for i in range(target.shape[1]): + if self.is_skewed(target[:, i]): + self.scaler.append( + FunctionTransformer(func=np.log1p, inverse_func=np.expm1) + ) + logger.info('Auto select robust transformer.') + else: + self.scaler.append(StandardScaler()) + self.scaler[-1].fit(target[:, i : i + 1]) + else: + if self.task == 'regression': + self.scaler = self.scaler_choose(self.ss_method, target) + self.scaler.fit(target) + elif self.task == 'multilabel_regression': + self.scaler = [] + for i in range(target.shape[1]): + self.scaler.append( + self.scaler_choose(self.ss_method, target[:, i : i + 1]) + ) + self.scaler[-1].fit(target[:, i : i + 1]) + try: + os.remove(os.path.join(dump_dir, 'target_scaler.ss')) + except: + pass + os.makedirs(dump_dir, exist_ok=True) + joblib.dump(self.scaler, os.path.join(dump_dir, 'target_scaler.ss')) + + def scaler_choose(self, method, target): + """""" + Selects the appropriate scaler based on the scaling method and fit it to the target. + + :param method: (str) The scaling method to be used. + + currently support: + + - 'minmax': MinMaxScaler, + + - 'standard': StandardScaler, + + - 'robust': RobustScaler, + + - 'maxabs': MaxAbsScaler, + + - 'quantile': QuantileTransformer, + + - 'power_trans': PowerTransformer, + + - 'normalizer': Normalizer, + + - 'log1p': FunctionTransformer, + + :param target: (array-like) The target values to fit the scaler. + :return: The fitted scaler object. + """""" + if method == 'minmax': + scaler = MinMaxScaler() + elif method == 'standard': + scaler = StandardScaler() + elif method == 'robust': + scaler = RobustScaler() + elif method == 'maxabs': + scaler = MaxAbsScaler() + elif method == 'quantile': + scaler = QuantileTransformer() + elif method == 'power_trans': + scaler = ( + PowerTransformer(method='box-cox') + if np.min(target) > 0 + else PowerTransformer(method='yeo-johnson') + ) + elif method == 'normalizer': + scaler = Normalizer() + elif method == 'log1p': + scaler = FunctionTransformer(func=np.log1p, inverse_func=np.expm1) + else: + raise ValueError('Unknown scaler method: {}'.format(method)) + return scaler + + def inverse_transform(self, target): + """""" + Inverse transforms the scaled target values back to their original scale. + + :param target: (array-like) The target values to be inverse transformed. + + :return: (array-like) The target values in their original scale. + """""" + if self.task in ['classification', 'multiclass', 'multilabel_classification']: + return target + if self.ss_method == 'none' or self.scaler is None: + return target + elif self.task == 'regression': + return self.scaler.inverse_transform(target) + elif self.task == 'multilabel_regression': + assert isinstance(self.scaler, list) and len(self.scaler) == target.shape[1] + new_target = np.zeros_like(target) + for i in range(target.shape[1]): + new_target[:, i] = ( + self.scaler[i] + .inverse_transform(target[:, i : i + 1]) + .reshape( + -1, + ) + ) + return new_target + else: + raise ValueError('Unknown scaler method: {}'.format(self.ss_method)) + + def is_skewed(self, target): + """""" + Determines whether the target values are skewed based on skewness and kurtosis metrics. + + :param target: (array-like) The target values to be checked for skewness. + + :return: (bool) True if the target is skewed, False otherwise. + """""" + if self.task in ['classification', 'multiclass', 'multilabel_classification']: + return False + else: + return abs(skew(target)) > 5.0 or abs(kurtosis(target)) > 20.0 +","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_conformer.py",".py","1094","40","import numpy as np +from unimol_tools.data.conformer import ( + inner_coords, + coords2unimol, + inner_smi2coords, + create_mol_from_atoms_and_coords, +) +from unimol_tools.data.dictionary import Dictionary + + +def test_inner_coords_and_coords2unimol(): + atoms = ['C', 'H', 'O'] + coords = [[0, 0, 0], [0, 0, 1], [1, 0, 0]] + no_h_atoms, no_h_coords = inner_coords(atoms, coords, remove_hs=True) + assert 'H' not in no_h_atoms + d = Dictionary() + for a in ['C', 'O']: + if a not in d: + d.add_symbol(a) + feat = coords2unimol(no_h_atoms, no_h_coords, d) + assert feat['src_tokens'].dtype == int + assert feat['src_coord'].shape[1] == 3 + + +def test_inner_smi2coords_returns_mol(): + mol = inner_smi2coords('CC', return_mol=True) + from rdkit.Chem import Mol + + assert isinstance(mol, Mol) + + +def test_create_mol_from_atoms_and_coords(): + atoms = ['C', 'O'] + coords = [[0, 0, 0], [1, 0, 0]] + mol = create_mol_from_atoms_and_coords(atoms, coords) + from rdkit.Chem import Mol + + assert isinstance(mol, Mol) + assert mol.GetNumAtoms() == 2 +","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_multiclass.py",".py","2194","78","import os +import zipfile +import pandas as pd +import numpy as np +import pytest +from utils_net import download_for_test + +from unimol_tools import MolTrain, MolPredict + +DATA_URL = 'https://weilab.math.msu.edu/DataLibrary/2D/Downloads/ESOL_smi.zip' + + +@pytest.mark.network +def test_multiclass_train_predict(tmp_path): + os.environ.setdefault('UNIMOL_WEIGHT_DIR', str(tmp_path / 'weights')) + zip_path = tmp_path / 'ESOL_smi.zip' + download_for_test( + DATA_URL, + zip_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + with zipfile.ZipFile(zip_path, 'r') as zf: + zf.extractall(tmp_path) + csv_path = tmp_path / 'ESOL.csv' + if not csv_path.exists(): + pytest.skip('Dataset missing after extraction') + df = pd.read_csv(csv_path) + # Filter for multiclass target + df = df[df['Number of H-Bond Donors'] <= 2] + if df.empty: + pytest.skip('No valid samples for multiclass classification') + # take 100 samples for testing + df = df.sample(n=100, random_state=42) + + data_dict = { + 'SMILES': df['smiles'].tolist(), + 'target': df['Number of H-Bond Donors'].tolist(), + } + + n = len(data_dict['SMILES']) + np.random.seed(42) + idx = np.random.permutation(n) + split = int(0.8 * n) + train_idx = idx[:split] + test_idx = idx[split:] + + train_dict = { + 'SMILES': [data_dict['SMILES'][i] for i in train_idx], + 'target': [data_dict['target'][i] for i in train_idx], + } + test_dict = { + 'SMILES': [data_dict['SMILES'][i] for i in test_idx], + 'target': [data_dict['target'][i] for i in test_idx], + } + + exp_dir = tmp_path / 'exp' + mclf = MolTrain( + task='multiclass', + data_type='molecule', + epochs=1, + batch_size=2, + kfold=2, + metrics='acc', + save_path=str(exp_dir), + ) + try: + mclf.fit(train_dict) + except Exception as e: + pytest.skip(f""Training failed: {e}"") + + predictor = MolPredict(load_model=str(exp_dir)) + preds = predictor.predict(data=test_dict) + assert len(preds) == len(test_dict['SMILES']) +","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_classification.py",".py","1781","58","import os +import zipfile +import pandas as pd +import pytest +from utils_net import download_for_test + +from unimol_tools import MolTrain, MolPredict + +DATA_URL = 'https://weilab.math.msu.edu/DataLibrary/2D/Downloads/Ames_smi.zip' + + +@pytest.mark.network +def test_classification_train_predict(tmp_path): + # ensure any pretrained weights are written to a temporary directory + os.environ.setdefault('UNIMOL_WEIGHT_DIR', str(tmp_path / 'weights')) + zip_path = tmp_path / 'Ames_smi.zip' + download_for_test( + DATA_URL, + zip_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + with zipfile.ZipFile(zip_path, 'r') as zf: + zf.extractall(tmp_path) + csv_path = tmp_path / 'Ames.csv' + if not csv_path.exists(): + pytest.skip('Dataset missing after extraction') + df = pd.read_csv(csv_path) + df = df.drop(columns=['CAS_NO']).rename(columns={'Activity': 'target'}) + # take 100 samples for testing + df = df.sample(n=100, random_state=42) + train_df = df.sample(frac=0.8, random_state=42) + test_df = df.drop(train_df.index) + train_data = train_df.to_dict(orient='list') + test_smiles = test_df['Canonical_Smiles'].tolist() + + exp_dir = tmp_path / 'exp' + clf = MolTrain( + task='classification', + data_type='molecule', + epochs=1, + batch_size=2, + kfold=2, + metrics='auc', + smiles_col='Canonical_Smiles', + save_path=str(exp_dir), + ) + try: + clf.fit(train_data) + except Exception as e: + pytest.skip(f""Training failed: {e}"") + + predictor = MolPredict(load_model=str(exp_dir)) + preds = predictor.predict(test_smiles) + assert len(preds) == len(test_smiles)","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_datascaler.py",".py","816","23","import numpy as np +from sklearn.preprocessing import PowerTransformer + +from unimol_tools.data.datascaler import TargetScaler + + +def test_target_scaler_roundtrip(tmp_path): + y = np.arange(6, dtype=float).reshape(-1, 1) + scaler = TargetScaler('standard', 'regression') + scaler.fit(y, str(tmp_path)) + scaled = scaler.transform(y) + restored = scaler.inverse_transform(scaled) + assert np.allclose(restored, y) + + +def test_power_trans_scaler_choice(): + scaler = TargetScaler('power_trans', 'regression') + pos_scaler = scaler.scaler_choose('power_trans', np.array([[1.0], [2.0]])) + neg_scaler = scaler.scaler_choose('power_trans', np.array([[-1.0], [2.0]])) + assert isinstance(pos_scaler, PowerTransformer) + assert pos_scaler.method == 'box-cox' + assert neg_scaler.method == 'yeo-johnson' +","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_multilabel_classification.py",".py","3296","109","import os +import gzip +import zipfile +import pandas as pd +import pytest +from utils_net import download_for_test +from rdkit.Chem import PandasTools + +from unimol_tools import MolTrain, MolPredict + +CSV_URL = 'https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/tox21.csv.gz' +SDF_URL = 'https://tripod.nih.gov/tox21/challenge/download?id=tox21_10k_data_allsdf' + + +@pytest.mark.network +def test_multilabel_csv(tmp_path): + os.environ.setdefault('UNIMOL_WEIGHT_DIR', str(tmp_path / 'weights')) + gz_path = tmp_path / 'tox21.csv.gz' + csv_path = tmp_path / 'tox21.csv' + download_for_test( + CSV_URL, + gz_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + with gzip.open(gz_path, 'rb') as fin, open(csv_path, 'wb') as fout: + fout.write(fin.read()) + df = pd.read_csv(csv_path) + df.fillna(0, inplace=True) + df.drop(columns=['mol_id'], inplace=True) + # take 1000 samples for testing + df = df.sample(n=1000, random_state=42) + train_df = df.sample(frac=0.8, random_state=42) + test_df = df.drop(train_df.index) + train_dict = train_df.to_dict(orient='list') + test_smiles = test_df['smiles'].tolist() + + exp_dir = tmp_path / 'exp' + mlclf = MolTrain( + task='multilabel_classification', + data_type='molecule', + epochs=1, + batch_size=8, + kfold=2, + metrics='auc', + smiles_col='smiles', + target_cols=[c for c in df.columns if c != 'smiles'], + save_path=str(exp_dir), + ) + try: + mlclf.fit(train_dict) + except Exception as e: + pytest.skip(f""Training failed: {e}"") + + predictor = MolPredict(load_model=str(exp_dir)) + preds = predictor.predict(test_smiles) + assert len(preds) == len(test_smiles) + + +@pytest.mark.network +def test_multilabel_sdf(tmp_path): + os.environ.setdefault('UNIMOL_WEIGHT_DIR', str(tmp_path / 'weights')) + zip_path = tmp_path / 'tox21.zip' + download_for_test( + SDF_URL, + zip_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + with zipfile.ZipFile(zip_path, 'r') as zf: + zf.extractall(tmp_path) + sdf_files = [p for p in tmp_path.rglob('*.sdf')] + if not sdf_files: + pytest.skip('SDF file not found after extraction') + sdf_path = sdf_files[0] + data = PandasTools.LoadSDF(str(sdf_path)) + data['SR-HSE'] = data['SR-HSE'].fillna(0) + data['NR-AR'] = data['NR-AR'].fillna(0) + # take 1000 samples for testing + data = data.sample(n=1000, random_state=42) + data_train = data.sample(frac=0.8, random_state=42) + data_test = data.drop(data_train.index) + + exp_dir = tmp_path / 'exp_sdf' + mlclf = MolTrain( + task='multilabel_classification', + data_type='molecule', + epochs=1, + batch_size=8, + kfold=2, + metrics='auc', + target_cols=['SR-HSE', 'NR-AR'], + save_path=str(exp_dir), + ) + try: + mlclf.fit(data_train) + except Exception as e: + pytest.skip(f""Training failed: {e}"") + + predictor = MolPredict(load_model=str(exp_dir)) + preds = predictor.predict(data_test) + assert len(preds) == len(data_test) +","Python" +"QSAR","deepmodeling/unimol_tools","tests/utils_net.py",".py","4160","138","from __future__ import annotations +from pathlib import Path +from typing import Optional, Tuple +import hashlib +import os + +import requests +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry + + +def _make_session( + max_retries: int = 5, + backoff_factor: float = 0.5, +) -> requests.Session: + sess = requests.Session() + retry = Retry( + total=max_retries, + connect=max_retries, + read=max_retries, + status=max_retries, + backoff_factor=backoff_factor, + status_forcelist=(429, 500, 502, 503, 504), + allowed_methods={""HEAD"", ""GET""}, + respect_retry_after_header=True, + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retry) + sess.mount(""http://"", adapter) + sess.mount(""https://"", adapter) + sess.headers.update({""User-Agent"": ""pytest-downloader/1.0""}) + return sess + + +def download( + url: str, + dest: Path, + *, + timeout: Tuple[float, float] = (5.0, 30.0), + max_retries: int = 5, + backoff_factor: float = 0.5, + chunk_size: int = 1 << 18, + allow_resume: bool = True, + expected_sha256: Optional[str] = None, + expected_md5: Optional[str] = None, + session: Optional[requests.Session] = None, +) -> Path: + dest = Path(dest) + dest.parent.mkdir(parents=True, exist_ok=True) + + if dest.exists() and (expected_sha256 or expected_md5): + ok = True + if expected_sha256: + ok &= _check_hash(dest, expected_sha256, ""sha256"") + if expected_md5: + ok &= _check_hash(dest, expected_md5, ""md5"") + if ok: + return dest + else: + dest.unlink(missing_ok=True) + + sess = session or _make_session(max_retries=max_retries, backoff_factor=backoff_factor) + + content_length = None + try: + h = sess.head(url, timeout=timeout, allow_redirects=True) + if h.ok: + content_length = _safe_int(h.headers.get(""Content-Length"")) + except requests.RequestException: + pass + + tmp_path = dest.with_suffix(dest.suffix + "".part"") + downloaded = tmp_path.stat().st_size if (allow_resume and tmp_path.exists()) else 0 + headers = {} + if allow_resume and downloaded > 0: + headers[""Range""] = f""bytes={downloaded}-"" + + with sess.get(url, timeout=timeout, stream=True, headers=headers) as r: + if r.status_code == 200 and ""Range"" in headers: + downloaded = 0 + r.raise_for_status() + mode = ""ab"" if downloaded > 0 else ""wb"" + with open(tmp_path, mode) as f: + for chunk in r.iter_content(chunk_size=chunk_size): + if chunk: + f.write(chunk) + + if content_length is not None: + actual = tmp_path.stat().st_size + if actual != content_length: + tmp_path.unlink(missing_ok=True) + raise IOError(f""Downloaded size mismatch: expected {content_length}, got {actual}"") + + if expected_sha256 and not _check_hash(tmp_path, expected_sha256, ""sha256""): + tmp_path.unlink(missing_ok=True) + raise IOError(""SHA-256 checksum mismatch."") + if expected_md5 and not _check_hash(tmp_path, expected_md5, ""md5""): + tmp_path.unlink(missing_ok=True) + raise IOError(""MD5 checksum mismatch."") + + os.replace(tmp_path, dest) + return dest + + +def download_for_test( + url: str, + dest: Path, + *, + skip_on_failure: bool = True, + **kwargs, +) -> Path: + try: + return download(url, dest, **kwargs) + except Exception as e: + if skip_on_failure: + try: + import pytest + pytest.skip(f""Skip due to network instability: {e}"") + except Exception: + pass + raise + + +def _check_hash(path: Path, expected_hex: str, algo: str) -> bool: + expected_hex = expected_hex.lower().strip() + h = hashlib.new(algo) + with open(path, ""rb"") as f: + for chunk in iter(lambda: f.read(1 << 20), b""""): + h.update(chunk) + return h.hexdigest() == expected_hex + + +def _safe_int(x: Optional[str]) -> Optional[int]: + try: + return int(x) if x is not None else None + except ValueError: + return None +","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_regression.py",".py","3707","127","import os +import numpy as np +import pytest +from rdkit import Chem +from utils_net import download_for_test + +from unimol_tools import MolTrain, MolPredict + +ESOL_TRAIN_URL = 'https://huggingface.co/datasets/HR-machine/ESol/resolve/main/train_data.csv?download=true' +ESOL_TEST_URL = 'https://huggingface.co/datasets/HR-machine/ESol/resolve/main/test_data.csv?download=true' +VQM24_URL = 'https://zenodo.org/records/15442257/files/DMC.npz?download=1' + + +@pytest.mark.network +def test_regression_esol(tmp_path): + train_csv = tmp_path / 'train.csv' + test_csv = tmp_path / 'test.csv' + download_for_test( + ESOL_TRAIN_URL, + train_csv, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + download_for_test( + ESOL_TEST_URL, + test_csv, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + + exp_dir = tmp_path / 'exp_esol' + reg = MolTrain( + task='regression', + data_type='molecule', + epochs=1, + batch_size=2, + kfold=2, + metrics='mae', + smiles_col='smiles', + target_cols=['ESOL predicted log solubility in mols per litre'], + save_path=str(exp_dir), + ) + reg.fit(str(train_csv)) + predictor = MolPredict(load_model=str(exp_dir)) + preds = predictor.predict(str(test_csv)) + assert len(preds) > 0 + + +@pytest.mark.network +def test_regression_vqm24(tmp_path): + npz_path = tmp_path / 'dmc.npz' + download_for_test( + VQM24_URL, + npz_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + expected_md5=""565e295d845662d7df8e0dcca6db0d21"", + skip_on_failure=True, + ) + data = np.load(npz_path, allow_pickle=True) + atoms_all = data['atoms'] + coords_all = data['coordinates'] + smiles_all = data['graphs'] + targets_all = data['Etot'] + + valid_smiles = [] + valid_atoms = [] + valid_coords = [] + valid_targets = [] + for smi, target, atoms, coords in zip(smiles_all, targets_all, atoms_all, coords_all): + try: + mol = Chem.MolFromSmiles(smi) + if mol is not None: + valid_smiles.append(smi) + valid_atoms.append(atoms) + valid_coords.append(coords) + valid_targets.append(target) + except Exception: + pass + # take 100 samples for testing + valid_smiles = valid_smiles[:100] + valid_atoms = valid_atoms[:100] + valid_coords = valid_coords[:100] + valid_targets = valid_targets[:100] + + n = len(valid_smiles) + np.random.seed(42) + idx = np.random.permutation(n) + split = int(0.8 * n) + train_idx = idx[:split] + test_idx = idx[split:] + + train_data = { + 'target': [valid_targets[i] for i in train_idx], + 'atoms': [valid_atoms[i] for i in train_idx], + 'coordinates': [valid_coords[i] for i in train_idx], + 'SMILES': [valid_smiles[i] for i in train_idx], + } + test_data = { + 'atoms': [valid_atoms[i] for i in test_idx], + 'coordinates': [valid_coords[i] for i in test_idx], + 'SMILES': [valid_smiles[i] for i in test_idx], + } + + exp_dir = tmp_path / 'exp_vqm' + reg = MolTrain( + task='regression', + data_type='molecule', + epochs=1, + batch_size=2, + kfold=2, + metrics='mae', + save_path=str(exp_dir), + ) + reg.fit(train_data) + predictor = MolPredict(load_model=str(exp_dir)) + preds = predictor.predict(data=test_data, save_path=str(tmp_path/'pred')) + assert len(preds) == len(test_idx) +","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_multilabel_regression.py",".py","3520","120","import os +import zipfile +import pandas as pd +import numpy as np +import pytest +from utils_net import download_for_test + +from unimol_tools import MolTrain, MolPredict + +DATA_URL = 'https://weilab.math.msu.edu/DataLibrary/2D/Downloads/FreeSolv_smi.zip' + + +@pytest.mark.network +def test_multilabel_regression_csv(tmp_path): + os.environ.setdefault('UNIMOL_WEIGHT_DIR', str(tmp_path / 'weights')) + zip_path = tmp_path / 'freesolv.zip' + download_for_test( + DATA_URL, + zip_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + with zipfile.ZipFile(zip_path, 'r') as zf: + zf.extractall(tmp_path) + csv_path = tmp_path / 'SAMPL.csv' + if not csv_path.exists(): + pytest.skip('Dataset missing after extraction') + df = pd.read_csv(csv_path) + # take 100 samples for testing + df = df.sample(n=100, random_state=42) + train_df = df.sample(frac=0.8, random_state=42) + test_df = df.drop(train_df.index) + train_path = tmp_path / 'train.csv' + test_path = tmp_path / 'test.csv' + train_df.to_csv(train_path, index=False) + test_df.to_csv(test_path, index=False) + + exp_dir = tmp_path / 'exp_csv' + mreg = MolTrain( + task='multilabel_regression', + data_type='molecule', + epochs=1, + batch_size=2, + kfold=2, + metrics='mae', + smiles_col='smiles', + target_cols='expt,calc', + save_path=str(exp_dir), + ) + try: + mreg.fit(str(train_path)) + except Exception as e: + pytest.skip(f""Training failed: {e}"") + + predictor = MolPredict(load_model=str(exp_dir)) + preds = predictor.predict(str(test_path)) + assert len(preds) == len(test_df) + + +@pytest.mark.network +def test_multilabel_regression_dict(tmp_path): + os.environ.setdefault('UNIMOL_WEIGHT_DIR', str(tmp_path / 'weights')) + zip_path = tmp_path / 'freesolv.zip' + download_for_test( + DATA_URL, + zip_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + with zipfile.ZipFile(zip_path, 'r') as zf: + zf.extractall(tmp_path) + csv_path = tmp_path / 'SAMPL.csv' + if not csv_path.exists(): + pytest.skip('Dataset missing after extraction') + df = pd.read_csv(csv_path) + # take 100 samples for testing + df = df.sample(n=100, random_state=42, ignore_index=True) + n = len(df) + np.random.seed(42) + idx = np.random.permutation(n) + split = int(0.8 * n) + train_idx = idx[:split] + test_idx = idx[split:] + train_dict = { + 'SMILES': [df['smiles'][i] for i in train_idx], + 'expt': [df['expt'][i] for i in train_idx], + 'calc': [df['calc'][i] for i in train_idx], + } + test_dict = { + 'SMILES': [df['smiles'][i] for i in test_idx], + 'expt': [df['expt'][i] for i in test_idx], + 'calc': [df['calc'][i] for i in test_idx], + } + + exp_dir = tmp_path / 'exp_dict' + mreg = MolTrain( + task='multilabel_regression', + data_type='molecule', + epochs=1, + batch_size=2, + kfold=2, + metrics='mae', + target_cols=['expt', 'calc'], + save_path=str(exp_dir), + ) + try: + mreg.fit(train_dict) + except Exception as e: + pytest.skip(f""Training failed: {e}"") + + predictor = MolPredict(load_model=str(exp_dir)) + preds = predictor.predict(data=test_dict) + assert len(preds) == len(test_idx) +","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_representation.py",".py","2933","94","import gzip +import zipfile +import numpy as np +import pandas as pd +import pytest +from utils_net import download_for_test +from rdkit.Chem import PandasTools + +from unimol_tools import UniMolRepr + +VQM24_URL = 'https://zenodo.org/records/15442257/files/DMC.npz?download=1' +TOX21_CSV_URL = 'https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/tox21.csv.gz' +TOX21_SDF_URL = 'https://tripod.nih.gov/tox21/challenge/download?id=tox21_10k_data_allsdf' + + +@pytest.mark.network +def test_unimol_repr_vqm24(tmp_path): + npz_path = tmp_path / 'DMC.npz' + download_for_test( + VQM24_URL, + npz_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + expected_md5=""565e295d845662d7df8e0dcca6db0d21"", + skip_on_failure=True, + ) + data = np.load(npz_path, allow_pickle=True) + atoms = data['atoms'][:100] + coords = data['coordinates'][:100] + smiles = data['graphs'][:100] + data_dict = { + 'SMILES': smiles.tolist(), + 'atoms': atoms.tolist(), + 'coordinates': coords.tolist(), + } + repr_model = UniMolRepr(batch_size=16) + try: + out = repr_model.get_repr(data_dict, return_atomic_reprs=True) + except Exception as e: + pytest.skip(f'representation failed: {e}') + assert 'cls_repr' in out and len(out['cls_repr']) == len(smiles) + + +@pytest.mark.network +def test_unimol_repr_tox21_csv(tmp_path): + gz_path = tmp_path / 'tox21.csv.gz' + csv_path = tmp_path / 'tox21.csv' + download_for_test( + TOX21_CSV_URL, + gz_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + with gzip.open(gz_path, 'rb') as fin, open(csv_path, 'wb') as fout: + fout.write(fin.read()) + df = pd.read_csv(csv_path).head(100) + repr_model = UniMolRepr(smiles_col='smiles', batch_size=32) + try: + tensor = repr_model.get_repr(df, return_tensor=True) + except Exception as e: + pytest.skip(f'representation failed: {e}') + assert tensor.shape[0] == len(df) + + +@pytest.mark.network +def test_unimol_repr_tox21_sdf(tmp_path): + zip_path = tmp_path / 'tox21.zip' + download_for_test( + TOX21_SDF_URL, + zip_path, + timeout=(5, 60), + max_retries=5, + backoff_factor=0.5, + allow_resume=True, + skip_on_failure=True, + ) + with zipfile.ZipFile(zip_path, 'r') as zf: + zf.extractall(tmp_path) + sdf_files = list(tmp_path.rglob('*.sdf')) + if not sdf_files: + pytest.skip('SDF file not found after extraction') + data = PandasTools.LoadSDF(str(sdf_files[0])).head(100) + repr_model = UniMolRepr(batch_size=16) + try: + out = repr_model.get_repr(data, return_atomic_reprs=True) + except Exception as e: + pytest.skip(f'representation failed: {e}') + assert isinstance(out, dict) and len(out['cls_repr']) == len(data) +","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_datareader.py",".py","1504","48","import pandas as pd +import numpy as np +import pytest +from unimol_tools.data.datareader import MolDataReader + + +def test_read_data_from_smiles_list(): + smiles = [""CCO"", ""C""] + reader = MolDataReader() + result = reader.read_data(smiles) + assert result[""smiles""] == smiles + assert len(result[""scaffolds""]) == len(smiles) + assert result[""raw_data""].shape[0] == len(smiles) + + +def test_check_smiles_behavior(): + reader = MolDataReader() + # invalid SMILES should return False during training when not strict + assert reader.check_smiles(""invalid"", is_train=True, smi_strict=False) is False + # invalid SMILES should raise in strict mode + with pytest.raises(ValueError): + reader.check_smiles(""invalid"", is_train=True, smi_strict=True) + + +def test_convert_numeric_columns(): + from rdkit import Chem + df = pd.DataFrame({ + ""ROMol"": [Chem.MolFromSmiles(""CCO"")], + ""num"": [""1""], + ""alpha"": [""a""], + }) + reader = MolDataReader() + out = reader._convert_numeric_columns(df.copy()) + assert pd.api.types.is_numeric_dtype(out[""num""]) + assert not pd.api.types.is_numeric_dtype(out[""alpha""]) + assert out[""ROMol""].iloc[0] == df[""ROMol""].iloc[0] + + +def test_anomaly_clean_regression(): + df = pd.DataFrame({ + ""SMILES"": [""C""] * 11, + ""TARGET"": [1] * 10 + [100], + }) + reader = MolDataReader() + cleaned = reader.anomaly_clean_regression(df, [""TARGET""]) + assert 100 not in cleaned[""TARGET""].values + assert len(cleaned) == 10 +","Python" +"QSAR","deepmodeling/unimol_tools","tests/test_metrics.py",".py","1588","48","import numpy as np +import torch + +from unimol_tools.utils.metrics import ( + cal_nan_metric, + multi_acc, + log_loss_with_label, + reg_preasonr, + reg_spearmanr, + Metrics, +) + + +def test_cal_nan_metric_ignores_nan(): + y_true = np.array([[1.0, np.nan], [2.0, 3.0]]) + y_pred = np.array([[1.5, 0.0], [2.5, 4.0]]) + mse = lambda a, b: ((a - b) ** 2).mean() + res = cal_nan_metric(y_true, y_pred, metric_func=mse) + assert np.isclose(res, 0.625) + + +def test_basic_metric_functions(): + assert np.isclose(reg_preasonr([1, 2], [1, 2]), 1.0) + assert np.isclose(reg_spearmanr([1, 2], [1, 2]), 1.0) + y_true = np.array([[0], [1], [2]]) + y_pred = np.array([[0.1, 0.9, 0.0], [0.2, 0.6, 0.2], [0.1, 0.2, 0.7]]) + assert np.isclose(multi_acc(y_true, y_pred), 2 / 3) + ll = log_loss_with_label([0, 1], [[0.8, 0.2], [0.2, 0.8]], labels=[0, 1]) + assert ll >= 0.0 + + +def test_metrics_classification_threshold(): + metric = Metrics('classification', metrics_str='acc') + target = np.array([[0], [1], [1], [0]]) + pred = np.array([[0.2], [0.8], [0.9], [0.1]]) + th = metric.calculate_single_classification_threshold(target, pred, step=5) + assert np.isclose(th, 0.3) + + +def test_metrics_calculation(): + cls = Metrics('classification', metrics_str='acc') + out = cls.cal_metric(np.array([[1], [0]]), np.array([[0.6], [0.3]])) + assert 'acc' in out and out['acc'] == 1.0 + + reg = Metrics('regression', metrics_str='mae') + out = reg.cal_metric(np.array([[1.0], [2.0]]), np.array([[1.5], [2.0]])) + assert 'mae' in out and np.isclose(out['mae'], 0.25) +","Python" +"QSAR","deepmodeling/unimol_tools","tests/conftest.py",".py","908","28","import os +import pytest + +@pytest.fixture(scope=""session"", autouse=True) +def set_unimol_weight_dir(tmp_path_factory): + """"""Ensure UNIMOL_WEIGHT_DIR is set to a temporary directory for tests."""""" + weight_dir = tmp_path_factory.mktemp(""weights"") + original = os.environ.get(""UNIMOL_WEIGHT_DIR"") + os.environ[""UNIMOL_WEIGHT_DIR""] = str(weight_dir) + yield + if original is None: + os.environ.pop(""UNIMOL_WEIGHT_DIR"", None) + else: + os.environ[""UNIMOL_WEIGHT_DIR""] = original + + +def pytest_addoption(parser): + parser.addoption(""--run-network"", action=""store_true"", help=""run tests that need network"") + + +def pytest_collection_modifyitems(config, items): + if config.getoption(""--run-network""): + return + skip_marker = pytest.mark.skip(reason=""need --run-network to run"") + for item in items: + if ""network"" in item.keywords: + item.add_marker(skip_marker) +","Python" +"QSAR","UnixJunkie/molenc","test_uhd.sh",".sh","329","15","#!/bin/bash + +# regression test for the UHD fingerprint +make + +# cleanup any prior run +\rm -f data/ethanol.uhd data/ethanol.smi.dix + +# run +_build/default/src/molenc_UHD.exe -f -i data/ethanol.smi -o data/ethanol.uhd + +# check Vs refs +diff data/ethanol.uhd data/ethanol.uhd.ref +diff data/ethanol.smi.dix data/ethanol.uhd.dix.ref +","Shell" +"QSAR","UnixJunkie/molenc","kb_test.sh",".sh","289","12","#!/bin/bash + +set -x + +~/src/molenc/kbe -i all_uniq_std.txt -k 64 > test_64_1xCPU.txt +sort test_64_1xCPU.txt -o test_64_1xCPU.txt + +~/src/molenc/kbe -np 16 -i all_uniq_std.txt -k 64 > test_64_16xCPU.txt +sort test_64_16xCPU.txt -o test_64_16xCPU.txt + +diff test_64_1xCPU.txt test_64_16xCPU.txt +","Shell" +"QSAR","UnixJunkie/molenc","test_BBAD.sh",".sh","1792","37","#!/bin/bash + +#set -x # DEBUG + +# check some properties of the AP-BBAD + +# 1) the BBAD of a single molecule is the encoded single molecule +rm -f caffeine_AP_BBAD.txt +_build/default/src/AP_BBAD.exe -i data/caffeine.smi -o caffeine_AP_BBAD.txt +awk -v sum=0 -F' ' '{sum += $2}END{if(sum == 105){print ""|features| OK""}}' caffeine_AP_BBAD.txt + +# 2) the BBAD computed in parallel is the same as the sequential one +rm -f seq_AD.txt par_AD.txt +_build/default/src/AP_BBAD.exe -i data/chembl1868_std.smi -o seq_AD.txt -np 1 +nprocs=`getconf _NPROCESSORS_ONLN` +_build/default/src/AP_BBAD.exe -i data/chembl1868_std.smi -o par_AD.txt -np ${nprocs} +diff seq_AD.txt par_AD.txt + +# 3) compute a simple BBAD by hand; check this is the one we obtain +rm -f data/alcools.AD.curr +_build/default/src/AP_BBAD.exe -i data/alcools.smi -o data/alcools.AD.curr +diff data/alcools.AD.curr data/alcools.AD.ref + +# 4) the BBAD of some molecules doesn't filter out any of those molecules +rm -f filtered.txt +_build/default/src/AP_BBAD.exe --bbad seq_AD.txt -i data/chembl1868_std.smi -o filtered.txt -np ${nprocs} +diff <(cat data/chembl1868_std.smi | wc -l) <(cat filtered.txt | wc -l) + +# 5) the BBAD union for two sets of molecules should be the same as the AD for the union of the sets +rm -f head_AD.txt tail_AD.txt head_tail_AD_union.txt head_tail_AD.txt +_build/default/src/AP_BBAD.exe -i <(head data/chembl1868_std.smi) -o head_AD.txt -np ${nprocs} +_build/default/src/AP_BBAD.exe -i <(tail data/chembl1868_std.smi) -o tail_AD.txt -np ${nprocs} +_build/default/src/AP_BBAD.exe --bbad head_AD.txt,tail_AD.txt -o head_tail_AD_union.txt +_build/default/src/AP_BBAD.exe -i <(head data/chembl1868_std.smi; tail data/chembl1868_std.smi) \ + -o head_tail_AD.txt +diff head_tail_AD_union.txt head_tail_AD.txt +","Shell" +"QSAR","UnixJunkie/molenc","smisur_test.sh",".sh","453","15","#!/bin/bash + +set -x #DEBUG + +# clean +rm -f data/chembl_antivirals.frags.smi data/chembl_antivirals.genmols.txt +# fragment +./bin/molenc_smisur.py --seed 1234 \ + -i data/chembl_antivirals.smi \ + -o data/chembl_antivirals.frags.smi +# assemble +./bin/molenc_smisur.py --seed 1234 --assemble \ + -i data/chembl_antivirals.frags.smi \ + -o data/chembl_antivirals.genmols.txt +","Shell" +"QSAR","UnixJunkie/molenc","deepsmi_test.sh",".sh","677","21","#!/bin/bash + +#set -x + +head ~/src/FMGO/data/TCM_20k.smi > input.smi +dos2unix input.smi +./bin/molenc_deepsmi.py --no-rings -i input.smi -o output.dsmi +./bin/molenc_deepsmi.py --no-rings -d -i output.dsmi -o output.smi +diff input.smi output.smi +rm -f output.{dsmi,smi} + +./bin/molenc_deepsmi.py --no-branches -i input.smi -o output.dsmi +./bin/molenc_deepsmi.py --no-branches -d -i output.dsmi -o output.smi +diff input.smi output.smi +rm -f output.{dsmi,smi} + +./bin/molenc_deepsmi.py --no-branches --no-rings -i input.smi -o output.dsmi +./bin/molenc_deepsmi.py --no-branches --no-rings -d -i output.dsmi -o output.smi +diff input.smi output.smi +rm -f output.{dsmi,smi} +","Shell" +"QSAR","UnixJunkie/molenc","mol_frag_test.sh",".sh","1308","39","#!/bin/bash + +# set -x #DEBUG + +# --view --> call mview on .smi files +MVIEW="""" +if [ ""$1"" == ""--view"" ] || [ ""$2"" == ""--view"" ]; then + MVIEW=""1"" +fi + +# --big --> work on the ""big"" dataset +BIG="""" +if [ ""$1"" == ""--big"" ] || [ ""$2"" == ""--big"" ]; then + BIG=""1"" +fi + +if [ ""$BIG"" == """" ]; then + # clean + rm -f data/3.to_frag data/3_frags.txt data/3_frags.smi \ + data/3_genmols.txt data/3_genmols.smi + # regen + ./bin/molenc_frag.py -i data/3.smi -o data/3.to_frag + [ ""$MVIEW"" == ""1"" ] && mview data/3.smi & + ./molenc_frag -im data/3.to_frag -of data/3_frags.txt -s 1234 + ./bin/molenc_frag2smi.py -i data/3_frags.txt -o data/3_frags.smi + [ ""$MVIEW"" == ""1"" ] && mview data/3_frags.smi & + ./molenc_frag -if data/3_frags.txt -om data/3_genmols.txt -s 1234 -n 20 + ./bin/molenc_mol2smi.py -i data/3_genmols.txt -o data/3_genmols.smi + cut -f1 data/3_genmols.smi | sort -u > data/3_genmols_uniq.smi + [ ""$MVIEW"" == ""1"" ] && mview data/3_genmols_uniq.smi & +else + IN=data/chembl_antivirals + ./bin/molenc_frag.py -i $IN.smi -o $IN.to_frag --draw + ./molenc_frag -im $IN.to_frag -of $IN.frags -s 1234 + ./bin/molenc_frag2smi.py -i $IN.frags -o $IN.frags.smi + ./molenc_frag -if $IN.frags -om $IN.mols -s 1234 -n 50 + ./bin/molenc_mol2smi.py -i $IN.mols -o $IN.mols.smi +fi +","Shell" +"QSAR","UnixJunkie/molenc","test_sdf_read.sh",".sh","310","10","#!/bin/bash + +set -x # DEBUG + +# check we parse correctly 10 3D molecules in a .sdf file +rm -f data/chembl30_10mols.txt.curr +_build/default/src/sdf_read.exe data/chembl30_10mols.sdf \ + > data/chembl30_10mols.txt.curr +diff data/chembl30_10mols.txt.ref data/chembl30_10mols.txt.curr +","Shell" +"QSAR","UnixJunkie/molenc","test.sh",".sh","828","21","#!/bin/bash + +#set -x # DEBUG + +# encoding an SDF or a SMILES file is the same +# and it is the one we expect +diff <(./bin/molenc_type_atoms.py data/caff_coca.sdf) data/caff_coca_types.ref +diff <(./bin/molenc_type_atoms.py data/caff_coca.smi) data/caff_coca_types.ref + +# ph4 features are the same than the ones extracted by ShowFeats.py +# (that were checked by hand and stored in a reference file) +diff <(./bin/molenc_ph4_type_atoms.py data/caff_coca.sdf) data/caff_coca_feats.ref + +diff <(_build/default/src/pubchem_decoder.exe -i data/test_in.pbc -o /dev/stdout) data/test_out.ref + +# atom pairs encoder tests +rm -f data/AP_test.smi.dix data/AP_test.txt # clean any previous run +molenc.sh --pairs -i data/AP_test.smi -o data/AP_test.txt +diff data/AP_test.smi.dix data/AP_test.smi.dix.ref +diff data/AP_test.txt data/AP_test.txt.ref +","Shell" +"QSAR","UnixJunkie/molenc","bin/molenc_diam.py",".py","1811","58","#!/usr/bin/env python3 +# +# Copyright (C) 2022, Francois Berenger +# Tsuda laboratory, Tokyo University, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# Compute the diamater of a molecule's 3D conformer +# i.e. largest interatomic distance + +import argparse, math, sys +from rdkit import Chem + +def euclid(xyz0, xyz1): + x0, y0, z0 = xyz0 + x1, y1, z1 = xyz1 + dx = x0 - x1 + dy = y0 - y1 + dz = z0 - z1 + return math.sqrt(dx*dx + dy*dy + dz*dz) + +# WARNING: O(n^2) +def diameter(mol): + num_atoms = mol.GetNumAtoms() + conf = mol.GetConformer(0) + diam = 0.0 + for i in range(num_atoms - 1): + xyz_i = conf.GetAtomPosition(i) + for j in range(i + 1, num_atoms): + xyz_j = conf.GetAtomPosition(j) + dist = euclid(xyz_i, xyz_j) + if dist > diam: + diam = dist + return diam + +if __name__ == '__main__': + # CLI options parsing + parser = argparse.ArgumentParser(description = + ""compute molecular diameter"") + parser.add_argument(""-i"", metavar = ""input.sdf"", dest = ""input_fn"", + help = ""3D conformer input file \ + (single molecule AND conformer)"") + # parse CLI --------------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + # parse CLI end ----------------------------------------------------------- + count = 0 + mol_supplier = Chem.SDMolSupplier(input_fn) + for mol in mol_supplier: + if (mol == None) or (count > 1): + assert(False) + count += 1 + diam = diameter(mol) + print(""%f"" % diam) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_gpc.py",".py","14879","395","#!/usr/bin/env python3 + +# Copyright (C) 2024, Francois Berenger +# Tsuda laboratory, Graduate School of Frontier Sciences, +# The University of Tokyo, Japan. +# +# Gaussian Process Classifier CLI wrapper +# input line format: '^SMILES\t[active]MOLNAME$' + +import argparse +import joblib # type: ignore +import math +import numpy as np +import os +import random +import rdkit +import sklearn # type: ignore +import sys +import tempfile +import time +import typing + +from rdkit import Chem, DataStructs +from rdkit.Chem import rdFingerprintGenerator +from sklearn.gaussian_process import GaussianProcessClassifier # type: ignore +from sklearn.gaussian_process.kernels import RBF # type: ignore +from sklearn.metrics import roc_auc_score, roc_curve # type: ignore + +def hour_min_sec() -> tuple[float, float, float]: + tm = time.localtime() + return (tm.tm_hour, tm.tm_min, tm.tm_sec) + +# use this instead of print to log on stderr +def log(*args, **kwargs): + hms = hour_min_sec() + print('%02d:%02d:%02d ' % hms, file=sys.stderr, end='') + return print(*args, **kwargs, file=sys.stderr) + +def abort_if(cond, err_msg): + if cond: + log(""%s"", err_msg) + sys.exit(1) + +def lines_of_file(fn): + with open(fn) as input: + return list(map(str.strip, input.readlines())) + +def train_test_split(train_portion, lines): + n = len(lines) + train_n = math.ceil(train_portion * n) + test_n = n - train_n + log('train/test: %d/%d' % (train_n, test_n)) + train = lines[0:train_n] + test = lines[train_n:] + assert(len(train) + len(test) == n) + return (train, test) + +def predict_classes(model, X_test) -> np.ndarray: + return model.predict(X_test) + +def predict_probas(model, X_test) -> np.ndarray: + probas = model.predict_proba(X_test) + # let's hope probas[:,1] are probabilities for the actives' class + return probas[:,1] + +def list_take_drop(l: list, n: int) -> tuple[list, list]: + took = l[0:n] + dropped = l[n:] + return (took, dropped) + +# cut list into several lists +def list_split(l, n): + x = float(len(l)) + test_n = math.ceil(x / float(n)) + # log('test_n: %d' % test_n) + res = [] + taken = [] + rest = l + for _i in range(0, n): + curr_test, curr_rest = list_take_drop(rest, test_n) + curr_train = taken + curr_rest + res.append((curr_train, curr_test)) + taken = taken + curr_test + rest = curr_rest + return res + +def parse_smiles_line(line: str) -> tuple[str, str, bool]: + # print(""DEBUG: %s"" % line) + split = line.strip().split() + assert(len(split) == 2) # ^SMILES\t[active]name$' + smi = split[0] + name = split[1] + label = name.startswith('active') + return (smi, name, label) + +def parse_smiles_lines(lines: list[str]) -> tuple[list[rdkit.Chem.rdchem.Mol], + list[str], + list[bool]]: + mols = [] + names = [] + labels = [] + for line in lines: + smi, name, label = parse_smiles_line(line) + mol = Chem.MolFromSmiles(smi) + if mol != None: + mols.append(mol) + names.append(name) + labels.append(label) + else: + log(""ERROR: molenc_gpc.py: parse_smiles_lines: could not parse smi for %s: %s"" % \ + (name, smi)) + return (mols, names, labels) + +def dump_pred_probas(output_fn, names, probas): + if len(names) != len(probas): + log('|names|=%d <> |probas|=%d' % (len(names), len(probas))) + exit(1) + if output_fn != '': + with open(output_fn, 'w') as output: + for name, p in zip(names, probas): + print('%s\t%f' % (name, p), file=output) + +def dump_pred_labels(output_fn, names, labels): + if len(names) != len(labels): + log('|names|=%d <> |probas|=%d' % (len(names), len(labels))) + exit(1) + if output_fn != '': + with open(output_fn, 'w') as output: + for name, label in zip(names, labels): + print('%s\t%d' % (name, label), file=output) + +def dump_score_labels(output_fn: str, + probas: list[float], + labels: list[bool]): + num_p = len(probas) + num_l = len(labels) + if num_p != num_l: + log('|probas|=%d <> |labels|=%d' % (num_p, num_l)) + exit(1) + with open(output_fn, 'w') as output: + for score, label in zip(probas, labels): + print('%f\t%d' % (score, label), file=output) + +def temp_file(prfx, sfx): + _, temp_fn = tempfile.mkstemp(prefix=prfx, suffix=sfx) + return temp_fn + +def gnuplot(title0, auc_curve_fn): + # escape underscores so that gnuplot doesn't interprete them + title = title0.replace('_', '\_') + gnuplot_commands = \ + [""set xlabel 'FPR'"", + ""set ylabel 'TPR'"", + ""set tics out nomirror"", + ""set size square"", + ""set xrange [0:1]"", + ""set yrange [0:1]"", + ""set key left"", + ""diag(x) = x"", + ""set title '%s'"" % title, + ""plot diag(x) not lc rgb 'black', '%s' u 1:2 w l t 'ROC'"" % auc_curve_fn] + # dump gnuplot commands + commands_temp_fn = temp_file(""gpr_"", "".gpl"") + with open(commands_temp_fn, 'w') as output: + for l in gnuplot_commands: + print(l, file=output) + os.system(""gnuplot --persist %s"" % commands_temp_fn) + os.remove(commands_temp_fn) # cleanup + +def ecfpX_of_mol(mol: rdkit.Chem.rdchem.Mol, radius) -> np.ndarray: + generator = rdFingerprintGenerator.GetMorganGenerator(radius, fpSize=2048) + fp = generator.GetFingerprint(mol) + arr = np.zeros((1,), int) + DataStructs.ConvertToNumpyArray(fp, arr) + # arr: np.ndarray of int64 w/ length 2048 + return arr + +def counted_atom_pairs_of_mol(mol): + generator = rdFingerprintGenerator.GetAtomPairGenerator(fpSize=8192, countSimulation=True) + fp = generator.GetFingerprint(mol) + arr = np.zeros((1,), int) + DataStructs.ConvertToNumpyArray(fp, arr) + return arr + +def ecfp4_of_mol(mol): + return ecfpX_of_mol(mol, 2) + +# parse SMILES, ignore names, read pIC50s then encode molecules w/ ECFP4 2048b +# return (X_train, y_train) +def read_SMILES_lines_class(lines, use_CAP=False): + mols, names, labels = parse_smiles_lines(lines) + X_train = None + if use_CAP: + X_train = np.array([counted_atom_pairs_of_mol(mol) for mol in mols]) + else: + X_train = np.array([ecfp4_of_mol(mol) for mol in mols]) + y_train = np.array(labels) + return (X_train, names, y_train) + +def gpc_train(X_train, y_train, seed=0): + if len(X_train) != len(y_train): + log('|X_train|=%d <> |y_train|=%d' % (len(X_train), len(y_train))) + exit(1) + rbf_k = 1.0 * RBF(1.0) + gpc = GaussianProcessClassifier(kernel=rbf_k, + random_state=seed, + optimizer='fmin_l_bfgs_b', + n_restarts_optimizer=5, + copy_X_train=True) + gpc.fit(X_train, y_train) + return gpc + +def gpc_train_test_NxCV(all_lines, cv_folds, use_CAP): + truth = [] + proba_preds = [] + fold = 0 + train_tests = list_split(all_lines, cv_folds) + for train_set, test_set in train_tests: + X_train, _names_train, y_train = read_SMILES_lines_class(train_set, use_CAP) + X_test, _names_test, y_ref = read_SMILES_lines_class(test_set, use_CAP) + model = gpc_train(X_train, y_train) + truth = truth + list(y_ref) + pred_probas = predict_probas(model, X_test) + roc_auc = roc_auc_score(y_ref, pred_probas) + log('fold: %d AUC: %.3f' % (fold, roc_auc)) + proba_preds = proba_preds + list(pred_probas) + fold += 1 + return (truth, proba_preds) + +def show_roc_curve(plot_title, pred_probas, true_labels): + auc_curve_fn = temp_file(""gpc_"", "".roc"") + # print('DEBUG: ROC AUC file: %s' % auc_curve_fn) + fpr, tpr, _thresholds = roc_curve(true_labels, pred_probas, pos_label=1) + with open(auc_curve_fn, 'wt') as output: + for fp, tp in zip(fpr, tpr): + print(""%g %g"" % (fp, tp), file=output) + gnuplot(plot_title, auc_curve_fn) + # cleanup + os.remove(auc_curve_fn) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser(description = 'train/use a GPC model') + parser.add_argument('-i', + metavar = '', type = str, + dest = 'input_fn', + help = 'input data file') + parser.add_argument('-o', + metavar = '', type = str, + dest = 'output_fn', + default = '', + help = 'predictions output file') + parser.add_argument('--save', + metavar = '', type = str, + dest = 'model_output_fn', + default = '', + help = 'trained model output file') + parser.add_argument('--load', + metavar = '', type = str, + dest = 'model_input_fn', + default = '', + help = 'trained model input file') + parser.add_argument('-s', + metavar = '', type = int, + dest = 'rng_seed', + default = -1, + help = 'RNG seed') + parser.add_argument('--no-compress', + action = ""store_true"", + dest = 'no_compress', + default = False, + help = 'turn off saved model compression') + parser.add_argument('--CAP', + action = ""store_true"", + dest = 'use_CAP', + default = False, + help = 'use counted atom pairs instead of ECFP4') + parser.add_argument('--no-plot', + action = ""store_true"", + dest = 'no_plot', + default = False, + help = 'do not show the ROC curve') + parser.add_argument('-np', + metavar = '', type = int, + dest = 'nprocs', + default = 1, + help = 'max number of processes') + parser.add_argument('-p', + metavar = '', type = float, + dest = 'train_p', + default = 0.8, + help = 'training set proportion') + parser.add_argument('--NxCV', + metavar = '', type = int, + dest = 'cv_folds', + default = 1, + help = 'number of cross validation folds') + # parse CLI --------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do: usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + model_input_fn = args.model_input_fn + model_output_fn = args.model_output_fn + abort_if(model_input_fn != '' and model_output_fn != '', + ""--load and --save are exclusive"") + rng_seed = args.rng_seed + if rng_seed != -1: + # only if the user asked for it, we make experiments repeatable + random.seed(rng_seed) + output_fn = args.output_fn + cv_folds = args.cv_folds + assert(cv_folds >= 1) + nprocs = args.nprocs + abort_if(nprocs < 1, 'nprocs must be >= 1') + train_p = args.train_p + if model_input_fn != '': + log('loading trained model: train_p <- 0.0') + train_p = 0.0 + if model_output_fn != '': + log('training prod model: train_p <- 1.0') + train_p = 1.0 + assert(0.0 <= train_p <= 1.0) + no_compress = args.no_compress + no_plot = args.no_plot + use_CAP = args.use_CAP + # work --------------------------------------------------------- + # read input + all_lines = lines_of_file(input_fn) + if train_p > 0.0: + # if not using a model in production but train-testing: + # break any ordering the input file might have + if rng_seed == -1: + log('WARN: all_lines shuffled w/o rng_seed (not reproducible)') + random.shuffle(all_lines) + model = None + train_lines = [] + test_lines = [] + if cv_folds == 1: + train_lines, test_lines = train_test_split(train_p, all_lines) + X_train, names_train, y_train = read_SMILES_lines_class(train_lines, use_CAP) + X_test, names_test, y_test = read_SMILES_lines_class(test_lines, use_CAP) + assert(len(X_train) == len(names_train) == len(y_train)) + assert(len(X_test) == len(names_test) == len(y_test)) + if model_input_fn != '': + log('loading model from %s' % model_input_fn) + model = joblib.load(model_input_fn) + else: + # print('|X_train|=%d' % len(X_train)) + # print('|y_train|=%d' % len(y_train)) + model = gpc_train(X_train, y_train) + if model_output_fn != '': + log('saving model to %s' % model_output_fn) + if no_compress: + joblib.dump(model, model_output_fn, compress=False) + else: + joblib.dump(model, model_output_fn, compress=3) + # predict w/ trained model + if train_p < 1.0: + pred_probas = predict_probas(model, X_test) + # print('|X_test|=%d' % len(X_test)) + # print('|y_test|=%d' % len(y_test)) + # print('|pred_probas|=%d' % len(pred_probas)) + dump_pred_probas(output_fn, names_test, pred_probas) + # print('t(y_test)=%s' % type(y_test)) + # print('t(pred_probas)=%s' % type(pred_probas)) + auc = roc_auc_score(y_test, pred_probas) + if train_p > 0.0: + # train/test case + title = ""GPC AUC=%.3f fn=%s"" % (auc, input_fn) + log(title) + if not no_plot: + show_roc_curve(title, pred_probas, y_test) + else: + # maybe production run or predictions + # on an external validation set + log('AUC: %.3f fn: %s !!! ONLY VALID if test set had target values !!!' % + (auc, input_fn)) + else: + assert(cv_folds > 1) + true_labels, preds = gpc_train_test_NxCV(all_lines, cv_folds, use_CAP) + assert(len(true_labels) == len(preds)) + auc = roc_auc_score(true_labels, preds) + auc_msg = 'GPC folds=%d AUC=%.3f fn=%s' % (cv_folds, auc, input_fn) + log(auc_msg) + # show the overall (all folds combined) ROC AUC curve + if not no_plot: + show_roc_curve(auc_msg, preds, true_labels) + after = time.time() + dt = after - before + log('dt: %.2f' % dt) +","Python" +"QSAR","UnixJunkie/molenc","bin/smi2png.py",".py","1437","48","#!/usr/bin/env python3 + +# One 2D picture SVG for each SMILES line +# molecule images are created in a created pix/ directory +# and named after their corresponding molecule + +import argparse +import rdkit +import os +import sys +from rdkit import Chem +from rdkit.Chem import AllChem +from rdkit.Chem.Draw import rdMolDraw2D + +def RobustMolSupplier(filename): + with open(filename) as f: + i = 0 + for line in f: + words = line.split() + index = i + i += 1 + smi = words[0] + name = words[1] + yield (index, name, Chem.MolFromSmiles(smi)) + +if __name__ == '__main__': + # parse CLI + # show help in case user has no clue of what to do + if len(sys.argv) != 2: + sys.stderr.write(""usage: %s input.smi\n"" % sys.argv[0]) + sys.exit(1) + input_smi = sys.argv[1] + if not (os.path.isdir('pix')): + os.mkdir('pix') + for i, name, mol in RobustMolSupplier(input_smi): + if mol is None: + continue + AllChem.Compute2DCoords(mol) # generate 2D conformer + d = rdMolDraw2D.MolDraw2DCairo(300, 300) # PNG output + # d.drawOptions().addAtomIndices = True + caption = '%d %s' % (i, name) + d.DrawMolecule(mol, legend = caption) + d.FinishDrawing() + out_fn = 'pix/%s.png' % name + print(""creating %s"" % out_fn) + with open(out_fn, 'wb') as out: + out.write(d.GetDrawingText()) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_smi2cansmi.py",".py","670","25","#!/usr/bin/env python3 + +# SMILES to RdKit canonical SMILES + +import sys + +from rdkit import Chem + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + smile, name = line.strip().split(""\t"") # enforce TAB-separated + try: + mol = Chem.MolFromSmiles(smile) + cano_smi = Chem.MolToSmiles(mol) + yield (cano_smi, name) + except Exception: + print(""ERROR: cannot parse: %s"" % line, + file=sys.stderr, end='') + +input_fn = sys.argv[1] + +for cano_smi, name in RobustSmilesMolSupplier(input_fn): + print('%s\t%s' % (cano_smi, name)) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_elements.py",".py","771","27","#!/usr/bin/env python3 + +# output to stdout elements found in each molecule +# INPUT: SMILES file +# OUTPUT: one symbol per line; several times if element present multiple times; +# hydrogens are made explicit + +import sys +from rdkit import Chem + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + smi, _name = line.strip().split(""\t"") # enforce TAB-separated + try: + yield Chem.MolFromSmiles(smi) + except Exception: + print(""ERROR: cannot parse: %s"" % line, + file=sys.stderr, end='') + +input_fn = sys.argv[1] + +for mol in RobustSmilesMolSupplier(input_fn): + mol_H = Chem.AddHs(mol) + for a in mol_H.GetAtoms(): + print(a.GetSymbol()) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_ph4.py",".py","11437","323","#!/usr/bin/env python3 +# +# Copyright (C) 2022, Francois Berenger +# Tsuda laboratory, The University of Tokyo, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# project molecules 3D conformers into the pharmacophore features/points space + +import argparse, math, os, sys, time +from rdkit import Chem + +# ph4 feature SMARTS from the Pharmer software +# definitions from Lidio Meireles and David Ryan Koes +# Article: https://doi.org/10.1021/ci200097m +# Code: https://raw.githubusercontent.com/UnixJunkie/pharmer/master/pharmarec.cpp +aro_smarts = [""a1aaaaa1"", + ""a1aaaa1""] + +hbd_smarts = [""[#7!H0&!$(N-[SX4](=O)(=O)[CX4](F)(F)F)]"", + ""[#8!H0&!$([OH][C,S,P]=O)]"", + ""[#16!H0]""] + +hba_smarts = [""[#7&!$([nX3])&!$([NX3]-*=[!#6])&!$([NX3]-[a])&!$([NX4])&!$(N=C([C,N])N)]"", + ""[$([O])&!$([OX2](C)C=O)&!$(*(~a)~a)]""] + +pos_smarts = [""[+,+2,+3,+4]"", + ""[$(CC)](=N)N"", # amidine + ""[$(C(N)(N)=N)]"", # guanidine + ""[$(n1cc[nH]c1)]""] + +neg_smarts = [""[-,-2,-3,-4]"", + ""C(=O)[O-,OH,OX1]"", + ""[$([S,P](=O)[O-,OH,OX1])]"", + ""c1[nH1]nnn1"", + ""c1nn[nH1]n1"", + ""C(=O)N[OH1,O-,OX1]"", + ""C(=O)N[OH1,O-]"", + ""CO(=N[OH1,O-])"", + ""[$(N-[SX4](=O)(=O)[CX4](F)(F)F)]""] # trifluoromethyl sulfonamide + +hyd_smarts = [""a1aaaaa1"", + ""a1aaaa1"", + # branched terminals as one point + ""[$([CH3X4,CH2X3,CH1X2,F,Cl,Br,I])&!$(**[CH3X4,CH2X3,CH1X2,F,Cl,Br,I])]"", + ""[$(*([CH3X4,CH2X3,CH1X2,F,Cl,Br,I])[CH3X4,CH2X3,CH1X2,F,Cl,Br,I])&!$(*([CH3X4,CH2X3,CH1X2,F,Cl,Br,I])([CH3X4,CH2X3,CH1X2,F,Cl,Br,I])[CH3X4,CH2X3,CH1X2,F,Cl,Br,I])]([CH3X4,CH2X3,CH1X2,F,Cl,Br,I])[CH3X4,CH2X3,CH1X2,F,Cl,Br,I]"", + ""*([CH3X4,CH2X3,CH1X2,F,Cl,Br,I])([CH3X4,CH2X3,CH1X2,F,Cl,Br,I])[CH3X4,CH2X3,CH1X2,F,Cl,Br,I]"", + # simple rings only; need to combine points to get good results for 3d structures + ""[C&r3]1~[C&r3]~[C&r3]1"", + ""[C&r4]1~[C&r4]~[C&r4]~[C&r4]1"", + ""[C&r5]1~[C&r5]~[C&r5]~[C&r5]~[C&r5]1"", + ""[C&r6]1~[C&r6]~[C&r6]~[C&r6]~[C&r6]~[C&r6]1"", + ""[C&r7]1~[C&r7]~[C&r7]~[C&r7]~[C&r7]~[C&r7]~[C&r7]1"", + ""[C&r8]1~[C&r8]~[C&r8]~[C&r8]~[C&r8]~[C&r8]~[C&r8]~[C&r8]1"", + # aliphatic chains + ""[CH2X4,CH1X3,CH0X2]~[CH3X4,CH2X3,CH1X2,F,Cl,Br,I]"", + ""[$([CH2X4,CH1X3,CH0X2]~[$([!#1]);!$([CH2X4,CH1X3,CH0X2])])]~[CH2X4,CH1X3,CH0X2]~[CH2X4,CH1X3,CH0X2]"", + ""[$([CH2X4,CH1X3,CH0X2]~[CH2X4,CH1X3,CH0X2]~[$([CH2X4,CH1X3,CH0X2]~[$([!#1]);!$([CH2X4,CH1X3,CH0X2])])])]~[CH2X4,CH1X3,CH0X2]~[CH2X4,CH1X3,CH0X2]~[CH2X4,CH1X3,CH0X2]"", + # sulfur (apparently) + ""[$([S]~[#6])&!$(S~[!#6])]""] + +def pattern_of_smarts(s): + return Chem.MolFromSmarts(s) + +# compile all SMARTS +aro_patterns = list(map(pattern_of_smarts, aro_smarts)) +hbd_patterns = list(map(pattern_of_smarts, hbd_smarts)) +hba_patterns = list(map(pattern_of_smarts, hba_smarts)) +pos_patterns = list(map(pattern_of_smarts, pos_smarts)) +neg_patterns = list(map(pattern_of_smarts, neg_smarts)) +hyd_patterns = list(map(pattern_of_smarts, hyd_smarts)) + +# geometric center of a matched pattern +# WARNING: single-conformer molecule is assumed +def average_match(mol, matched_pattern): + avg_x = 0.0 + avg_y = 0.0 + avg_z = 0.0 + count = float(len(matched_pattern)) + conf0 = mol.GetConformer(0) + for i in matched_pattern: + xyz = conf0.GetAtomPosition(i) + avg_x += xyz.x + avg_y += xyz.y + avg_z += xyz.z + center = (avg_x / count, + avg_y / count, + avg_z / count) + return center + +def find_matches(mol, patterns): + res = [] + for pat in patterns: + # get all matches for that pattern + matched = mol.GetSubstructMatches(pat) + for m in matched: + # get the center of each matched group + avg = average_match(mol, m) + res.append(avg) + return res + +def find_ARO(mol): + return find_matches(mol, aro_patterns) + +def find_HBD(mol): + return find_matches(mol, hbd_patterns) + +def find_HBA(mol): + return find_matches(mol, hba_patterns) + +def find_POS(mol): + return find_matches(mol, pos_patterns) + +def find_NEG(mol): + return find_matches(mol, neg_patterns) + +def euclid(xyz0, xyz1): + x0, y0, z0 = xyz0 + x1, y1, z1 = xyz1 + dx = x0 - x1 + dy = y0 - y1 + dz = z0 - z1 + return math.sqrt(dx*dx + dy*dy + dz*dz) + +def average(l): + sum_x = 0.0 + sum_y = 0.0 + sum_z = 0.0 + n = float(len(l)) + for (x, y, z) in l: + sum_x += x + sum_y += y + sum_z += z + return (sum_x / n, + sum_y / n, + sum_z / n) + +def find_HYD(cluster_HYD, mol): + hydros = find_matches(mol, hyd_patterns) + if not cluster_HYD: + return hydros + else: + # regroup all hydrophobic features within 2.0A + res = [] + n = len(hydros) + idx2cluster = list(range(n)) + for i in range(n): + h_i = hydros[i] + cluster_id = idx2cluster[i] + for j in range(i+1, n): + h_j = hydros[j] + if euclid(h_i, h_j) <= 2.0: + # same cluster + idx2cluster[j] = cluster_id + cluster_ids = set(idx2cluster) + for cid in cluster_ids: + group = [] + for i, h in enumerate(hydros): + if idx2cluster[i] == cid: + group.append(h) + res.append(average(group)) + return res + +def prfx_print(prfx, out, positions_3d): + for (x, y, z) in positions_3d: + out.write(""%s %g %g %g\n"" % (prfx, x, y, z)) + +def bild_print(out, comment, color, trans, radius, feats): + if len(feats) > 0: + out.write("".comment %s\n"" % comment) + out.write("".color %s\n"" % color) + out.write("".transparency %g\n"" % trans) + for (x, y, z) in feats: + out.write("".sphere %g %g %g %g\n"" % (x, y, z, radius)) + +def bild_print_ARO(out, feats): + bild_print(out, ""ARO"", ""green"", 0.75, 1.5, feats) + +def bild_print_HYD(out, feats): + bild_print(out, ""HYD"", ""grey"", 0.75, 1.5, feats) + +def bild_print_HBD(out, feats): + bild_print(out, ""HBD"", ""white"", 0.75, 1.25, feats) + +def bild_print_HBA(out, feats): + bild_print(out, ""HBA"", ""orange"", 0.75, 1.25, feats) + +def bild_print_POS(out, feats): + bild_print(out, ""POS"", ""blue"", 0.75, 1.0, feats) + +def bild_print_NEG(out, feats): + bild_print(out, ""NEG"", ""red"", 0.75, 1.0, feats) + +def print_ARO(out, aromatics): + prfx_print(""ARO"", out, aromatics) + +def print_HBD(out, donors): + prfx_print(""HBD"", out, donors) + +def print_HBA(out, acceptors): + prfx_print(""HBA"", out, acceptors) + +def print_POS(out, positives): + prfx_print(""POS"", out, positives) + +def print_NEG(out, negatives): + prfx_print(""NEG"", out, negatives) + +def print_HYD(out, hydrophobes): + prfx_print(""HYD"", out, hydrophobes) + +# better than default readline() never throwing an exception +def read_line_EOF(input): + line = input.readline() + if line == """": + raise EOFError + else: + return line + +# list all molecule names +def names_of_sdf_file(input_fn): + try: + with open(input_fn, 'r') as input: + fst_name = read_line_EOF(input).strip() + yield fst_name + while True: + line = read_line_EOF(input).strip() + while line != ""$$$$"": + line = read_line_EOF(input).strip() + next_name = read_line_EOF(input).strip() + yield next_name + except EOFError: + pass + +def path_prepend(dir, fn): + if dir == '': + return fn + else: + return (dir + '/' + fn) + +def bild_output(input_dir, mol_name, + aromatics, donors, acceptors, + positives, negatives, hydrophobes): + bild_fn = path_prepend(input_dir, mol_name + "".bild"") + with open(bild_fn, 'w') as bild_out: + bild_print_ARO(bild_out, aromatics) + bild_print_HBD(bild_out, donors) + bild_print_HBA(bild_out, acceptors) + bild_print_POS(bild_out, positives) + bild_print_NEG(bild_out, negatives) + bild_print_HYD(bild_out, hydrophobes) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""compute pharmacophore features for 3D molecules"") + parser.add_argument(""-i"", metavar = ""input.sdf"", dest = ""input_fn"", + help = ""conformers input file"") + parser.add_argument(""-o"", metavar = ""output.ph4"", dest = ""output_fn"", + help = ""ph4 features output file"") + parser.add_argument('--bild', dest='output_bild', + action='store_true', default=False, + help = ""output BILD files for visu in chimera"") + parser.add_argument('--no-group', dest='cluster_HYD', + action='store_false', default=True, + help = ""turn OFF grouping of HYD features"") + parser.add_argument('--permissive', dest='sanitize', + action='store_false', default=True, + help = ""turn OFF rdkit valence check"") + # parse CLI --------------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output_fn = args.output_fn + mol_names = names_of_sdf_file(input_fn) + input_dir = os.path.dirname(input_fn) + sanitize = args.sanitize + mol_supplier = Chem.SDMolSupplier(input_fn, sanitize=sanitize) + output_bild = args.output_bild + cluster_HYD = args.cluster_HYD + # parse CLI end ----------------------------------------------------------- + count = 0 + errors = 0 + with open(output_fn, 'w') as out: + for mol, name in zip(mol_supplier, mol_names): + if not sanitize: + mol.UpdatePropertyCache(strict=False) + Chem.SanitizeMol(mol, + Chem.SANITIZE_SYMMRINGS | \ + Chem.SANITIZE_SETCONJUGATION | \ + Chem.SANITIZE_SETHYBRIDIZATION) + # print(""%d atoms"" % mol.GetNumHeavyAtoms(), file=sys.stderr) + if mol == None: + errors += 1 + else: + aromatics = find_ARO(mol) + donors = find_HBD(mol) + acceptors = find_HBA(mol) + positives = find_POS(mol) + negatives = find_NEG(mol) + hydrophobes = find_HYD(cluster_HYD, mol) + num_feats = sum(map(len, [aromatics, donors, acceptors, + positives, negatives, hydrophobes])) + out.write(""%d:%s\n"" % (num_feats, name)) + print_ARO(out, aromatics) + print_HBD(out, donors) + print_HBA(out, acceptors) + print_POS(out, positives) + print_NEG(out, negatives) + print_HYD(out, hydrophobes) + if output_bild: + bild_output(input_dir, name, + aromatics, donors, acceptors, + positives, negatives, hydrophobes) + count += 1 + after = time.time() + dt = after - before + print(""%d molecules @ %.2fHz; %d errors"" % (count, count / dt, errors), + file=sys.stderr) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_uniq.py",".py","460","22","#!/usr/bin/env python3 +# +# only print on stdout a line if its key was never seen before + +import sys + +input_fn = sys.argv[1] +sep = sys.argv[2] +# user-provided field number, as in awk, start at 1 +field = int(sys.argv[3]) - 1 + +seen = {} + +for line in open(input_fn).readlines(): + strip = line.strip() + toks = strip.split(sep) + key = toks[field] + already_seen = seen.get(key, False) + if not already_seen: + print(line) + seen[key] = True +","Python" +"QSAR","UnixJunkie/molenc","bin/inchi2smi.py",".py","855","33","#!/usr/bin/env python3 + +# InChI to SMILES conversion + +import argparse +import rdkit +import sys +from rdkit import Chem + +def RobustMolSupplier(filename): + with open(filename) as f: + for line in f: + words = line.split() + name = words[0] + inchi = words[1] + yield (name, Chem.MolFromInchi(inchi)) + +if __name__ == '__main__': + # parse CLI + # show help in case user has no clue of what to do + if len(sys.argv) != 3: + sys.stderr.write(""%s input.inchi output.smi\n"" % sys.argv[0]) + sys.exit(1) + input_inchi = sys.argv[1] + output_smi = sys.argv[2] + output = open(output_smi, 'w') + for name, mol in RobustMolSupplier(input_inchi): + if mol is None: + continue + smi = Chem.MolToSmiles(mol) + output.write(""%s\t%s\n"" % (smi, name)) + output.close() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_color.py",".py","2497","68","#!/usr/bin/env python3 + +# color molecules from a SMILES file according to per-atom delta score +# values from another file + +import matplotlib.pyplot as plot +import rdkit, sys +from rdkit import Chem +from rdkit.Chem import Draw +from rdkit.Chem.Draw import rdDepictor, SimilarityMaps + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + words = line.split() + smile = words[0] + name = "" "".join(words[1:]) # everything after the SMILES string + yield (name, Chem.MolFromSmiles(smile)) + +# draw all atoms in black +drawOptions = Draw.DrawingOptions() +drawOptions.elemDict = {} +drawOptions.bgColor = None + +if __name__ == '__main__': + if len(sys.argv) != 3: + print(""usage: %s molecules.smi molecules.delta"" % sys.argv[0]) + exit(1) + smiles_fn = sys.argv[1] + deltas_fn = sys.argv[2] + delta_max = 0.1 # arbitrary, to normalize deltas and color-scale them + delta_file = open(deltas_fn, 'r') + count = 0 + for long_name, mol in RobustSmilesMolSupplier(smiles_fn): + # split by '_' in case name was postfixed with underscores + # and additional data + name = long_name.split('_')[0] + line = delta_file.readline() + words = line.split() + curr_name = words[0] + if curr_name != name: + print(""names differ: %s != %s"" % (name, curr_name)) + exit(1) + delta_strings = words[1:] + nb_deltas = len(delta_strings) + nb_atoms = mol.GetNumAtoms() + assert(nb_deltas == nb_atoms) + deltas = list(map(lambda x: float(x), delta_strings)) + rdDepictor.Compute2DCoords(mol) # 2D conformer for figure + # compute similarity map weights + weights = [] + for delta in deltas: + # run-time check that delta is not too high or delta_max too small + assert(delta <= delta_max) + weight = delta / delta_max + weights.append(weight) + sim_map = Draw.SimilarityMaps.\ + GetSimilarityMapFromWeights(mol, weights, size = (200,200), + options=drawOptions, + scale=50.0) + # the bbox param forces centering the molecule in the figure + sim_map.savefig(name + '.svg', bbox_inches = 'tight') + plot.close(sim_map) + count += 1 + print('processed: %d\r' % count, end='') + print('processed: %d' % count) + delta_file.close() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_drug.py",".py","1776","54","#!/usr/bin/env python3 +# +# Copyright (C) 2023, Francois Berenger +# Tsuda laboratory, The University of Tokyo, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# Drug-like filter: only drug-like molecules will be printed on stdout + +import sys + +from rdkit import Chem +from rdkit.Chem import Descriptors + +# Tran-Nguyen, V. K., Jacquemard, C., & Rognan, D. (2020). +# LIT-PCBA: An unbiased data set for machine learning and virtual screening. +# Journal of chemical information and modeling, 60(9), 4263-4273. +def drug_like_filter(mol): + MolW = Descriptors.MolWt(mol) + if MolW <= 150 or MolW >= 800: # 150 < MolW < 800 Da + return False + cLogP = Descriptors.MolLogP(mol) + if cLogP <= -3.0 or cLogP >= 5.0: # −3.0 < AlogP < 5.0 + return False + RotB = Descriptors.NumRotatableBonds(mol) + if RotB >= 15: # RotB < 15 + return False + HBA = Descriptors.NumHAcceptors(mol) + if HBA >= 10: # HBA < 10 + return False + HBD = Descriptors.NumHDonors(mol) + if HBD >= 10: # HBD < 10 + return False + FC = Chem.rdmolops.GetFormalCharge(mol) + if FC <= -2 or FC >= 2: # −2.0 < FC < 2.0 + return False + return True # Still here? Drug-like then! + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + smile, name = line.strip().split(""\t"") # enforce TAB-separated + try: + mol = Chem.MolFromSmiles(smile) + yield (mol, smile, name) + except Exception: + print(""ERROR: cannot parse: %s"" % line, + file=sys.stderr, end='') + +input_fn = sys.argv[1] + +for mol, smile, name in RobustSmilesMolSupplier(input_fn): + if drug_like_filter(mol): + print('%s\t%s' % (smile, name)) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_SA.py",".py","5804","155","#!/usr/bin/env python3 + +# calculation of synthetic accessibility score as described in: +# +# Estimation of Synthetic Accessibility Score of Drug-like Molecules based on Molecular Complexity and Fragment Contributions +# Peter Ertl and Ansgar Schuffenhauer +# Journal of Cheminformatics 1:8 (2009) +# http://www.jcheminf.com/content/1/1/8 +# +# several small modifications to the original paper are included +# particularly slightly different formula for marocyclic penalty +# and taking into account also molecule symmetry (fingerprint density) +# +# for a set of 10k diverse molecules the agreement between the original method +# as implemented in PipelinePilot and this implementation is r2 = 0.97 +# +# peter ertl & greg landrum, september 2013 +# +# Copyright (c) 2013, Novartis Institutes for BioMedical Research Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Novartis Institutes for BioMedical Research Inc. +# nor the names of its contributors may be used to endorse or promote +# products derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from rdkit import Chem +from rdkit.Chem import rdMolDescriptors +import pickle + +import math +from collections import defaultdict + +import os.path as op + +_fscores = None + +def readFragmentScores(name='fpscores'): + import gzip + global _fscores + # generate the full path filename: + if name == ""fpscores"": + name = op.join(op.dirname(__file__), name) + data = pickle.load(gzip.open('%s.pkl.gz' % name)) + outDict = {} + for i in data: + for j in range(1, len(i)): + outDict[i[j]] = float(i[0]) + _fscores = outDict + +def numBridgeheadsAndSpiro(mol, ri=None): + nSpiro = rdMolDescriptors.CalcNumSpiroAtoms(mol) + nBridgehead = rdMolDescriptors.CalcNumBridgeheadAtoms(mol) + return nBridgehead, nSpiro + +def calculateScore(m): + if _fscores is None: + readFragmentScores() + # fragment score + fp = rdMolDescriptors.GetMorganFingerprint(m, + 2) # <- 2 is the *radius* of the circular fingerprint + fps = fp.GetNonzeroElements() + score1 = 0. + nf = 0 + for bitId, v in fps.items(): + nf += v + sfp = bitId + score1 += _fscores.get(sfp, -4) * v + score1 /= nf + # features score + nAtoms = m.GetNumAtoms() + nChiralCenters = len(Chem.FindMolChiralCenters(m, includeUnassigned=True)) + ri = m.GetRingInfo() + nBridgeheads, nSpiro = numBridgeheadsAndSpiro(m, ri) + nMacrocycles = 0 + for x in ri.AtomRings(): + if len(x) > 8: + nMacrocycles += 1 + sizePenalty = nAtoms**1.005 - nAtoms + stereoPenalty = math.log10(nChiralCenters + 1) + spiroPenalty = math.log10(nSpiro + 1) + bridgePenalty = math.log10(nBridgeheads + 1) + macrocyclePenalty = 0. + # --------------------------------------- + # This differs from the paper, which defines: + # macrocyclePenalty = math.log10(nMacrocycles+1) + # This form generates better results when 2 or more macrocycles are present + if nMacrocycles > 0: + macrocyclePenalty = math.log10(2) + score2 = 0. - sizePenalty - stereoPenalty - spiroPenalty - bridgePenalty - macrocyclePenalty + # correction for the fingerprint density + # not in the original publication, added in version 1.1 + # to make highly symmetrical molecules easier to synthetise + score3 = 0. + if nAtoms > len(fps): + score3 = math.log(float(nAtoms) / len(fps)) * .5 + sascore = score1 + score2 + score3 + # need to transform ""raw"" value into scale between 1 and 10 + min = -4.0 + max = 2.5 + sascore = 11. - (sascore - min + 1) / (max - min) * 9. + # smooth the 10-end + if sascore > 8.: + sascore = 8. + math.log(sascore + 1. - 9.) + if sascore > 10.: + sascore = 10.0 + elif sascore < 1.: + sascore = 1.0 + + return sascore + +def processMols(mols): + for m, smi, name in mols: + if m != None: + s = calculateScore(m) + print('%s\t%s\t%.2f' % (smi, name, s)) + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + stripped = line.strip() + words = stripped.split() + smile = words[0] + name = words[1] + yield (Chem.MolFromSmiles(smile), smile, name) + +if __name__ == '__main__': + import sys + import time + readFragmentScores(""fpscores"") + # suppl = Chem.SmilesMolSupplier(sys.argv[1]) + suppl = RobustSmilesMolSupplier(sys.argv[1]) + processMols(suppl) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_lead.py",".py","2264","57","#!/usr/bin/env python3 +# +# Copyright (C) 2022, Francois Berenger +# Tsuda laboratory, The University of Tokyo, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# lead-like filter: only lead-like molecules will be printed on stdout + +import sys + +from rdkit import Chem +from rdkit.Chem import Descriptors + +# Oprea's lead-like filter +# Hann, M. M., & Oprea, T. I. (2004). +# Pursuing the leadlikeness concept in pharmaceutical research. +# Current opinion in chemical biology, 8(3), 255-263. +def lead_like(mol): + # MolW <= 460 + if Descriptors.MolWt(mol) > 460: + return False + # -4.0 <= LogP <= 4.2 + LogP = Descriptors.MolLogP(mol) + if LogP < -4.0 or LogP > 4.2: + return False + # # LogSw >= -5 # ignored + # rotB <= 10 + if Descriptors.NumRotatableBonds(mol) > 10: + return False + # nRings <= 4 (number of SSSR rings, _not_ aromatic rings) + if len(Chem.GetSSSR(mol)) > 4: + return False + # HBD <= 5 + if Descriptors.NumHDonors(mol) > 5: + return False + # HBA <= 9 + if Descriptors.NumHAcceptors(mol) > 9: + return False + return True # lead-like then! + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + smile, name = line.strip().split(""\t"") # enforce TAB-separated + try: + mol = Chem.MolFromSmiles(smile) + yield (mol, smile, name) + except Exception: + print(""ERROR: cannot parse: %s"" % line, + file=sys.stderr, end='') + +input_fn = sys.argv[1] + +for mol, smile, name in RobustSmilesMolSupplier(input_fn): + if lead_like(mol): + print('%s\t%s' % (smile, name)) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_scaffold.py",".py","3812","106","#!/usr/bin/env python3 + +# Copyright (C) 2020, Francois Berenger +# Yamanishi laboratory, +# Department of Bioscience and Bioinformatics, +# Faculty of Computer Science and Systems Engineering, +# Kyushu Institute of Technology, +# 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan. +# +# Compute the Bemis-Murcho generic scaffold (framework) +# of each input molecule. +# And yes, the rdkit implementation of them is not faithful +# to the published article: +# Bemis, G. W., & Murcko, M. A. (1996). +# ""The properties of known drugs. 1. Molecular frameworks."" +# Journal of medicinal chemistry, 39(15), 2887-2893. + +import argparse, rdkit, sys +from rdkit import Chem + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + words = line.split() + smi = words[0] + name = words[1] + mol = Chem.MolFromSmiles(smi) + yield (smi, name, mol) + +# only correct for a molecule whose hydrogens have been deleted previously +def find_terminal_atoms(mol): + res = [] + for a in mol.GetAtoms(): + if a.GetDegree() == 1: + res.append(a) + return res + +def BemisMurckoFramework(mol): + # keep only Heavy Atoms (HA) + only_HA = rdkit.Chem.rdmolops.RemoveHs(mol) + # switch all HA to Carbon + rw_mol = Chem.RWMol(only_HA) + for i in range(rw_mol.GetNumAtoms()): + rw_mol.ReplaceAtom(i, Chem.Atom(6)) + # switch all non single bonds to single + non_single_bonds = [] + for b in rw_mol.GetBonds(): + if b.GetBondType() != Chem.BondType.SINGLE: + non_single_bonds.append(b) + for b in non_single_bonds: + j = b.GetBeginAtomIdx() + k = b.GetEndAtomIdx() + rw_mol.RemoveBond(j, k) + rw_mol.AddBond(j, k, Chem.BondType.SINGLE) + # as long as there are terminal atoms, remove them + terminal_atoms = find_terminal_atoms(rw_mol) + while terminal_atoms != []: + for a in terminal_atoms: + for b in a.GetBonds(): + rw_mol.RemoveBond(b.GetBeginAtomIdx(), b.GetEndAtomIdx()) + rw_mol.RemoveAtom(a.GetIdx()) + terminal_atoms = find_terminal_atoms(rw_mol) + return rw_mol.GetMol() + +def main(): + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""Append Bemis-Murcko scaffold to each input molecule"") + parser.add_argument(""-i"", metavar = ""input_smi"", dest = ""input_smi"", + help = ""input SMILES file"") + parser.add_argument(""-o"", metavar = ""output_smi"", dest = ""output_smi"", + help = ""output SMILES file"") + parser.add_argument('--new-line', dest='new_line', + action='store_true', default=False, + help = ""insert a newline before the scaffold"") + # parse CLI + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_smi = args.input_smi + output_smi = args.output_smi + new_line = args.new_line + out_count = 0 + error_count = 0 + with open(output_smi, 'w') as out_file: + for smi, name, mol in RobustSmilesMolSupplier(input_smi): + if mol is None: + error_count += 1 + else: + scaff = BemisMurckoFramework(mol) + scaff_smi = Chem.MolToSmiles(scaff) + if new_line: + print(""%s\t%s\n%s"" % (smi, name, scaff_smi), file=out_file) + else: + print(""%s\t%s\t%s"" % (smi, name, scaff_smi), file=out_file) + out_count += 1 + total_count = out_count + error_count + print(""encoded: %d errors: %d total: %d"" % + (out_count, error_count, total_count), + file=sys.stderr) + +if __name__ == '__main__': + main() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_common.py",".py","9234","263"," +import numpy, rdkit, re, sys + +from rdkit import Chem +from rdkit.Chem.AtomPairs import Pairs +from enum import IntEnum + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + smile, name = line.strip().split(""\t"") # enforce TAB-separated + mol = Chem.MolFromSmiles(smile) + mol.SetProp(""name"", name) + yield (name, mol) + +def RobustSmilesSupplier(filename): + with open(filename) as f: + for line in f: + smile, name = line.strip().split(""\t"") # enforce TAB-separated + yield (smile, name) + +def sort_pairs(pairs): + res = [] + for (a, b) in pairs: + x = min(a, b) + y = max(a, b) + res.append((x,y)) + return res + +# in a bond: atom with lowest index first +# in a list of bonds: bond with lowest first atom index first +def order_bonds_canonically(bonds): + pairs = map(lambda b: (b.GetBeginAtomIdx(), b.GetEndAtomIdx()), bonds) + min_index_first = sort_pairs(pairs) + min_index_first.sort() + return min_index_first + +def print_bonds(out, mol): + print(""#bonds:%d"" % mol.GetNumBonds(), file=out) + bonds = order_bonds_canonically(mol.GetBonds()) + for b in bonds: + print(""%d %d"" % b, file=out) + +def print_distance_matrix(out, mol, threeD): + if threeD: + # we use a histogram with bin width 1A + # this allows to work in 3D, at the cost of much more features + mat = Chem.Get3DDistanceMatrix(mol) + diam = int(numpy.max(mat)) + print(""#diameter:%d"" % diam, file=out) + nb_atoms = mol.GetNumAtoms() + for i in range(nb_atoms): + for j in range(nb_atoms): + x = int(mat[i][j]) + if j == 0: + print(""%d"" % x, end='', file=out) + else: + print("" %d"" % x, end='', file=out) + print("""", file=out) # newline + else: + mat = Chem.GetDistanceMatrix(mol) + diam = numpy.max(mat) + print(""#diameter:%d"" % diam, file=out) + nb_atoms = mol.GetNumAtoms() + for i in range(nb_atoms): + for j in range(nb_atoms): + x = mat[i][j] + if j == 0: + print(""%d"" % x, end='', file=out) + else: + print("" %d"" % x, end='', file=out) + print("""", file=out) # newline + +# ""#atoms:15 NCGC00261552-01_f00"" +def read_atoms_header(line): + (atoms, nb_atoms, name) = [t(s) for t,s in zip((str,int,str), + re.split('[: ]', line))] + assert(atoms == ""#atoms"") + return (nb_atoms, name) + +# ""0 0,6,2,0"" +def read_atom(line): + (index, nb_pi, atomic_num, nb_HA, charge, stereo) = [t(s) for t,s in + zip((int,int,int,int,int,int), + re.split('[, ]', line))] + return (index, nb_pi, atomic_num, nb_HA, charge, stereo) + +# ""#bonds:16"" +def read_bonds_header(line): + (bonds, nb_bonds) = [t(s) for t,s in + zip((str,int), + re.split('[:]', line))] + assert(bonds == ""#bonds"") + return nb_bonds + +def bond_type_of_char(c): + if c == '-': + return rdkit.Chem.rdchem.BondType.SINGLE + elif c == ':': + return rdkit.Chem.rdchem.BondType.AROMATIC + elif c == '=': + return rdkit.Chem.rdchem.BondType.DOUBLE + elif c == '#': + return rdkit.Chem.rdchem.BondType.TRIPLE + else: + assert(""molenc_common.py: bond_type_of_char"" == """") + +def parse_bond_stereo_string(stereo_str): + if stereo_str == ""N"": + return (rdkit.Chem.rdchem.BondStereo.STEREONONE, -1, -1) + else: + (stereo_char, a, b) = [t(s) for t,s in zip((str,int,int), + re.split(':', stereo_str))] + if stereo_char == ""A"": + return (rdkit.Chem.rdchem.BondStereo.STEREOANY, a, b) + elif stereo_char == ""Z"": + return (rdkit.Chem.rdchem.BondStereo.STEREOZ, a, b) + elif stereo_char == ""E"": + return (rdkit.Chem.rdchem.BondStereo.STEREOE, a, b) + elif stereo_char == ""C"": + return (rdkit.Chem.rdchem.BondStereo.STEREOCIS, a, b) + elif stereo_char == ""T"": + return (rdkit.Chem.rdchem.BondStereo.STEREOTRANS, a, b) + else: + assert(""molenc_common.py: stereo_char not in ['A','Z','E','C','T']"" == """") + +# ^0 - 1 N$ (no stereo) +# ^1 = 2 Z:0:3$ (some stereo) +def read_bond(line): + (start_i, c, stop_i, stereo_str) = [t(s) for t,s in zip((int,str,int,str), + re.split('[ ]', line))] + stereo = parse_bond_stereo_string(stereo_str) + return (start_i, bond_type_of_char(c), stop_i, stereo) + +class End_of_file(Exception): + """"""End of file was reached"""""" + pass + +# stereo information encoding using integers +class StereoCodes(IntEnum): + NONE = 0 # default unless specified otherwise + ANY_CENTER = 1 + R_CENTER = 2 + S_CENTER = 3 + ANY_BOND = 4 + Z_BOND = 5 + E_BOND = 6 + CIS_BOND = 7 + TRANS_BOND = 8 + +def atom_stereo_code_to_chiral_tag(c): + if c == 1: + return Chem.ChiralType.CHI_UNSPECIFIED + elif c == 2: + return Chem.ChiralType.CHI_TETRAHEDRAL_CW + elif c == 3: + return Chem.ChiralType.CHI_TETRAHEDRAL_CCW + else: + assert(""molenc_common.py: atom_stereo_code not in [1,2,3]"" == """") + +def bond_stereo_code_to_bond_stereo(c): + if c == 0: + return rdkit.Chem.rdchem.BondStereo.STEREONONE + elif c == 4: + return rdkit.Chem.rdchem.BondStereo.STEREOANY + elif c == 5: + return rdkit.Chem.rdchem.BondStereo.STEREOZ + elif c == 6: + return rdkit.Chem.rdchem.BondStereo.STEREOE + elif c == 7: + return rdkit.Chem.rdchem.BondStereo.STEREOCIS + elif c == 8: + return rdkit.Chem.rdchem.BondStereo.STEREOTRANS + else: + assert(""molenc_common.py: bond_stereo_code not in [0,4,5,6,7,8]"" == """") + +def char_of_bond_stereo(st): + if st == rdkit.Chem.rdchem.BondStereo.STEREONONE: + return 'N' + elif st == rdkit.Chem.rdchem.BondStereo.STEREOANY: + return 'A' + elif st == rdkit.Chem.rdchem.BondStereo.STEREOZ: + return 'Z' + elif st == rdkit.Chem.rdchem.BondStereo.STEREOE: + return 'E' + elif st == rdkit.Chem.rdchem.BondStereo.STEREOCIS: + return 'C' + elif st == rdkit.Chem.rdchem.BondStereo.STEREOTRANS: + return 'T' + else: + assert(""molenc_common.py: unexpected bond_stereo"" == """") + +def nb_heavy_atom_neighbors(a): + res = 0 + for neighb in a.GetNeighbors(): + if neighb.GetAtomicNum() != 1: + res += 1 + return res + +def get_stereo_center_indexes(m): + res = {} + # unassigned stereo centers are not reported; + # use includeUnassigned=True to change + for i, k in Chem.FindMolChiralCenters(m): + res[i] = True + return res + +def type_atom(a): + # stereo chemistry is ignored for the moment + nb_pi_electrons = Pairs.Utils.NumPiElectrons(a) + atom_num = a.GetAtomicNum() + nbHA = nb_heavy_atom_neighbors(a) + formal_charge = a.GetFormalCharge() + # make this easy to parse / unambiguous + res = ""%d,%d,%d,%d"" % (nb_pi_electrons, atom_num, nbHA, formal_charge) + return res + +def log_protected_bond(debug, name, b): + if debug: + print('mol %s: protected bond %d' % (name, b.GetIdx()), file=sys.stderr) + +# only single bonds not in rings, no stereo bonds, +# no bond to/from a specified stereo center (i.e. if stereo was set, +# we protect it) +def find_cuttable_bonds(mol, debug = False): + name = mol.GetProp(""name"") + stereo_center_indexes = get_stereo_center_indexes(mol) + for b in mol.GetBonds(): + # protect bonds to/from a stereo center + i = b.GetBeginAtomIdx() + j = b.GetEndAtomIdx() + if ((stereo_center_indexes.get(i) == True) or + (stereo_center_indexes.get(j) == True)): + b.SetBoolProp(""protected"", True) + log_protected_bond(debug, name, b) + # protect bonds between stereo bond atoms and their stereo atoms + if b.GetStereo() != rdkit.Chem.rdchem.BondStereo.STEREONONE: + (k, l) = b.GetStereoAtoms() + b0 = mol.GetBondBetweenAtoms(i, k) + b1 = mol.GetBondBetweenAtoms(i, l) + b2 = mol.GetBondBetweenAtoms(j, k) + b3 = mol.GetBondBetweenAtoms(j, l) + if b0 != None: + b0.SetBoolProp(""protected"", True) + log_protected_bond(debug, name, b0) + if b1 != None: + b1.SetBoolProp(""protected"", True) + log_protected_bond(debug, name, b1) + if b2 != None: + b2.SetBoolProp(""protected"", True) + log_protected_bond(debug, name, b2) + if b3 != None: + b3.SetBoolProp(""protected"", True) + log_protected_bond(debug, name, b3) + res = [] + for b in mol.GetBonds(): + if ((b.GetBondType() == rdkit.Chem.rdchem.BondType.SINGLE) and + (not b.IsInRing()) and + (b.GetStereo() == rdkit.Chem.rdchem.BondStereo.STEREONONE) and + (b.HasProp(""protected"") == 0)): # HasProp returns an int... :( + res.append(b) + return res +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_padel.py",".py","4512","125","#!/usr/bin/env python3 +# +# Copyright (C) 2022, Francois Berenger +# Tsuda laboratory, Graduate School of Frontier Sciences, +# The University of Tokyo, Japan. +# +# Encode molecules using PaDEL molecular descriptors. +# +# Yap, C. W. (2011). PaDEL‐descriptor: An open source software to calculate molecular descriptors and fingerprints. Journal of computational chemistry, 32(7), 1466-1474. + +import argparse, padelpy, re, sys + +regex = re.compile('\s') + +def find_whitespace(s): + m = re.search(regex, s) + if m == None: + return -1 + else: + return m.start() + +def parse_smiles_line(line): + fst_white = find_whitespace(line) + smi = '' + name = '' + if fst_white == -1: + # no whitespace separator: assume molecule has no name + # use the SMILES itself as the name, so this unnamed + # molecule will percolate instead of behing lost + smi = line + name = line + else: + smi = line[0:fst_white] + name = line[fst_white + 1:] + return (smi, name) + +def SmilesReader(filename): + with open(filename) as f: + for line in f.readlines(): + stripped = line.strip() + yield parse_smiles_line(stripped) + +num_descriptors = 1875 # on 12/10/2022 + +# line with only default values since PaDEL crashed +def all_missing(mol_name, def_val): + res = mol_name + tok = "",%s"" % def_val + for _i in range(1875): + res += tok + return res + +def main(): + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""Project molecules read from a SMILES file into the \ + PaDEL descriptors space"") + parser.add_argument(""-i"", metavar = ""input_smi"", dest = ""input_smi"", + help = ""input SMILES file"") + parser.add_argument(""-o"", metavar = ""output_csv"", dest = ""output_csv"", + help = ""output CSV file"") + parser.add_argument('--no-header', dest='no_header', + action='store_true', default=False, + help = ""no CSV header in output file"") + parser.add_argument('--NA', dest='use_NAs', + action='store_true', default=False, + help = ""use \""NA\"" instead of 0 for missing values"") + # parse CLI + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_smi = args.input_smi + output_csv = args.output_csv + no_header = args.no_header + use_NAs = args.use_NAs + default_value = ""0"" + if use_NAs: + default_value = ""\""NA\"""" + # end CLI parsing --------------------------------------------------------- + total = 0 + errors = 0 + start = True + # FBR: we don't handle the case where the 1st molecule would crash PaDEL + # in that case we don't even know what the CSV header should be + with open(output_csv, 'w') as out_file: + for smi, name in SmilesReader(input_smi): + descriptors = {} + try: + descriptors = padelpy.from_smiles(smi) + except: + errors += 1 + print(""KO: %s"" % smi, file=sys.stderr) + if (not no_header) and start: + if errors == 1: + print(""molenc_padel.py: error on 1st molecule: %s"" % smi, + file=sys.stderr) + sys.exit(1) + print(""\""name\"""", end='', file=out_file) + for k in descriptors: + print("",\""%s\"""" % k, end='', file=out_file) + print("""", file=out_file) # '\n' + start = False + # print all values; start line with molecule name (double quoted) + to_print = ""\""%s\"""" % name + for _k, v in descriptors.items(): + if v == '': + # always a joy with molecular descriptors: some + # of them cannot be computed for all molecules... + to_print += "",%s"" % default_value + else: + to_print += "",%g"" % float(v) + if descriptors == {}: + # robust to PaDEL crashing on some molecules + to_print = all_missing(name, default_value) + else: + assert(len(descriptors) == num_descriptors) + print(to_print, file=out_file) + total += 1 + print(""encoded: %d errors: %d"" % (total, errors), file=sys.stderr) + +if __name__ == '__main__': + main() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_sdf2smi.py",".py","481","19","#!/usr/bin/env python3 + +import argparse + +from rdkit import Chem +from rdkit.Chem.rdmolfiles import SmilesWriter + +parser = argparse.ArgumentParser() +parser.add_argument('inputfile', help=""sdf input file"") +parser.add_argument('outputfile', help=""smi output file"") +args = parser.parse_args() +sdf = Chem.SDMolSupplier(args.inputfile) +writer = SmilesWriter(args.outputfile, delimiter='\t', includeHeader=False) + +for mol in sdf: + if mol is not None: + writer.write(mol) +writer.close() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_sdf_strip.py",".py","680","30","#!/usr/bin/env python3 + +# remove listed tags from a .sdf file +# usage: molenc_sdf_strip.py input.sdf "",,..."" > stripped.sdf + +import sys + +sdf_fn = sys.argv[1] +tags = sys.argv[2] # coma-separated list of tags to remove + +tags_list = tags.split(',') +tags_set = set(tags_list) + +skip = False + +def endswith_any(line, tset): + for tag in tset: + if line.endswith(tag): + return True + return False + +for line in open(sdf_fn).readlines(): + stripped = line.strip() + if endswith_any(stripped, tags_set): + skip = True # the tag line itself + elif skip: + skip = False # the line after + else: + print(line, end='') # any other line +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_mview.py",".py","4494","121","#!/usr/bin/env python3 + +# create an HTML table to view all molecules in a web browser +# .smi, .sdf and .mol2 files are supported + +import argparse, mols2grid, os, rdkit, sys +from rdkit import Chem +from rdkit.Chem import AllChem, rdFMCS +import rdkit.Chem.rdDepictor +from rdkit.Chem.rdDepictor import ConstrainedDepictionParams + +def sdf_read_mols(fn): + suppl = Chem.SDMolSupplier(fn) + return [mol for mol in suppl] + +# in a proper .smi file: the first field is the SMILES string +# what's left on the right of it is the molecule's name +def mol_of_smi_line(line): + strip = line.strip() + words = strip.split() + smi = words[0] + name = words[1] + mol = Chem.MolFromSmiles(smi) + mol.SetProp('name', name) + return mol + +def smi_read_mols(fn): + lines = open(fn, 'r').readlines() + return [mol_of_smi_line(line) for line in lines] + +def main(): + subset = [""img""] + # ------------------------------------------------------------------- + parser = argparse.ArgumentParser( + description = ""output a molecules grid to an html file"") + parser.add_argument(""-i"", metavar = ""input_fn"", dest = ""input_fn"", + help = ""input file {smi|sdf|mol2}"") + parser.add_argument(""-o"", metavar = ""output_fn"", dest = ""output_fn"", + help = ""output file (html)"") + parser.add_argument(""-c"", metavar = ""num_cols"", dest = ""n_cols"", + type = int, default = 5, + help = ""number of columns (default=5)"") + parser.add_argument('-s', dest='show_names', + action='store_true', default=False, + help = ""show molecule names"") + parser.add_argument('-a', dest='align', + action='store_true', default=False, + help = ""_try_ to depict similarly each pair of molecules"") + # handle options + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output_fn = args.output_fn + n_cols = args.n_cols + show_names = args.show_names + align_2D_drawings = args.align + # ------------------------------------------------------------------ + if show_names: + subset=[""img"", ""name""] + mols = [] + # ----- SDF ----- + if input_fn.endswith("".sdf""): + # with some CLI options, we could select a subset: + # top 50, i..j, last 50, etc. + mols = sdf_read_mols(input_fn) + # ----- MOL2 ----- + elif input_fn.endswith("".mol2""): + print(""MOL2: not supported by rdkit; converting to sdf via obabel..."", file=sys.stderr) + input_sdf = input_fn + "".sdf"" + cmd = ""obabel %s -O %s"" % (input_fn, input_sdf) + print(""trying: %s"" % cmd, file=sys.stderr) + os.system(cmd) + mols = sdf_read_mols(input_sdf) + # ----- SMILES ----- + elif input_fn.endswith("".smi""): + mols = smi_read_mols(input_fn) + else: + print(""unsupported file type: %s"" % input_fn, file=sys.stderr) + exit(1) + + # try to have pairs of molecules w/ matching 2D drawing/orientation + # e.g. mol_0 must be aligned to mol_1, mol_2 to mol_3, etc. + errors = 0 + if align_2D_drawings: + # precalculate 2D coords for all mols + for mol in mols: + AllChem.Compute2DCoords(mol) + i = 0 + params = ConstrainedDepictionParams() + params.alignOnly = True + while i < len(mols) - 1: + mcs = rdFMCS.FindMCS([mols[i], mols[i+1]]) + mcs_smarts = mcs.smartsString + mcs_mol = Chem.MolFromSmarts(mcs_smarts) + # common reference drawing + AllChem.Compute2DCoords(mcs_mol) + AllChem.GenerateDepictionMatching2DStructure(mols[i], mcs_mol, params=params) + AllChem.GenerateDepictionMatching2DStructure(mols[i+1], mcs_mol, params=params) + i += 2 + if errors > 0: + print(""WARN: superposition errors: %d"" % errors, file=sys.stderr) + + # create HTML document + mols2grid.save(mols, + subset = subset, + n_cols = n_cols, + # size = (300, 350), + use_coords = align_2D_drawings, + output=output_fn, template=""static"", prerender=True) + + # view in browser + cmd = ""firefox %s"" % output_fn + print(""trying: %s"" % cmd, file=sys.stderr) + os.system(cmd) + +if __name__ == '__main__': + main() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_rfr.py",".py","22530","561","#!/usr/bin/env python3 + +# Copyright (C) 2024, Francois Berenger +# Tsuda laboratory, Graduate School of Frontier Sciences, +# The University of Tokyo, Japan. +# +# Random Forests Regressor or Classifier (RFR or RFC) CLI wrapper + +import argparse +import math +import os +import random +import scipy # type:ignore +import sklearn # type:ignore +import sys +import tempfile +import time +import typing +import joblib # type:ignore + +from sklearn.linear_model import ElasticNet, ElasticNetCV # type:ignore +from sklearn.ensemble import RandomForestRegressor # type:ignore +from sklearn.ensemble import RandomForestClassifier # type:ignore +from sklearn.metrics import r2_score, root_mean_squared_error # type:ignore +from scipy import sparse + +# FBR: TODO NxCV should really be parallelized... + +def hour_min_sec(): + tm = time.localtime() + return (tm.tm_hour, tm.tm_min, tm.tm_sec) + +# use this instead of print to log on stderr +def log(*args, **kwargs): + hms = hour_min_sec() + print('%02d:%02d:%02d ' % hms, file=sys.stderr, end='') + return print(*args, **kwargs, file=sys.stderr) + +def abort_if(cond, err_msg): + if cond: + log(""%s"", err_msg) + sys.exit(1) + +def count_lines_of_file(fn): + count = 0 + with open(fn) as input: + for _l in input: + count += 1 + return count + +def lines_of_file(fn): + with open(fn) as input: + return list(map(str.strip, input.readlines())) + +# current training-set line format example: +# mol_0,0.0,[1:23;8:3;22:2;45:6;56:1] +def split_AP_line(line): + fields = line.split(',') + name = str(fields[0]) + pIC50 = float(fields[1]) + feat_val_strings = fields[2] + return (name, pIC50, feat_val_strings) + +def string_contains(s, x): + try: + _i = s.index(x) + return True + except: + return False + +def read_features(row, col, data, i, max_feat_idx, feat_vals_str): + # print('feat_vals: %d' % (len(feat_vals))) + feat_vals = feat_vals_str.strip('[]') + for feat_val in feat_vals.split(';'): + if string_contains(feat_val, "":""): + feat_str, val_str = feat_val.split(':') + feat = int(feat_str) + val = float(val_str) + # print('%d:%d' % (feat, val)) + # assert(feat <= max_feat_idx) + if feat > max_feat_idx: + print(""molenc_rfr.py: read_features: \ +feat > max_feat_idx: %d > %d"" % (feat, max_feat_idx), + file=sys.stderr) + sys.exit(1) + if val != 0.0: + row.append(i) + col.append(feat) + data.append(val) + else: + print(""error: molenc_rfr.py: read_features: \ +ignoring molecule w/o feature at line %d"" % i, file=sys.stderr) + +def read_AP_lines_regr(max_feature_index, lines): + nb_lines = len(lines) + pIC50s = [] + row = [] + col = [] + data = [] + for i, line in enumerate(lines): + try: + # if line.endswith(""[]""): + # print(""molenc_rfr.py: read_AP_lines_regr: \ + # ignoring molecule w/o features at line %d: %s"" % (i, line), + # file=sys.stderr) + # else: + _name, pIC50, features_str = split_AP_line(line) + # log('%d %f' % (i, pIC50)) + pIC50s.append(pIC50) + read_features(row, col, data, i, max_feature_index, features_str) + except: + print(""molenc_rfr.py: read_AP_lines_regr: \ +cannot parse line %d: %s"" % (i, line), + file=sys.stderr) + raise + X = sparse.csr_matrix((data, (row, col)), + shape=(nb_lines, max_feature_index + 1)) + log('read_AP_lines_regr: (%d,%d)' % (X.shape[0], X.shape[1])) + return (X, pIC50s) + +def label_of_name(name): + if name.startswith('active'): + return 1 + else: + return 0 + +def read_AP_lines_class(max_feature_index, lines): + nb_lines = len(lines) + names = [] + labels = [] + row = [] + col = [] + data = [] + for i, line in enumerate(lines): + name, _pIC50, features_str = split_AP_line(line) + names.append(name) + labels.append(label_of_name(name)) + read_features(row, col, data, i, max_feature_index, features_str) + X = sparse.csr_matrix((data, (row, col)), + shape=(nb_lines, max_feature_index + 1)) + log('read_AP_lines_class: (%d,%d)' % (X.shape[0], X.shape[1])) + return (names, X, labels) + +def train_test_split(train_portion, lines): + n = len(lines) + train_n = math.ceil(train_portion * n) + test_n = n - train_n + log('train/test: %d/%d' % (train_n, test_n)) + train = lines[0:train_n] + test = lines[train_n:] + assert(len(train) + len(test) == n) + return (train, test) + +def train_regr(ntrees, crit, nprocs, msl, max_features, max_samples, + X_train, y_train): + log('regressor training...') + model = RandomForestRegressor(n_estimators = ntrees, + criterion = crit, + n_jobs = nprocs, + oob_score = True, + min_samples_leaf = msl, + max_features = max_features, + max_samples = max_samples) + model.fit(X_train, y_train) + return model + +# WARNING: in binary classification, y_train must be only 0s and 1s +def train_class_RFC(ntrees, nprocs, msl, max_features, X_train, y_train): + log('RFC classifier training...') + model = RandomForestClassifier(n_estimators = ntrees, + criterion = 'gini', + n_jobs = nprocs, + oob_score = True, + min_samples_leaf = msl, + max_features = max_features) + model.fit(X_train, y_train) + return model + +def train_class_ElN(nprocs, X_train, y_train): + log('ElasticNet classifier training...') + model = ElasticNetCV(cv=5, n_jobs=nprocs, random_state=314159265, + selection='random') + # model = ElasticNet(alpha=0.004517461806329454, l1_ratio=0.5, random_state=314159265, + # selection='random') + model.fit(X_train, y_train) + # e.g. alpha=0.004517461806329454 l1_ratio=0.5 + log('ElasticNet: alpha=%f l1_ratio=%f' % (model.alpha_, model.l1_ratio_)) + return model + +def test(model, X_test): + return model.predict(X_test) + +def list_take_drop(l, n): + took = l[0:n] + dropped = l[n:] + return (took, dropped) + +# cut list into several lists +def list_split(l, n): + x = float(len(l)) + test_n = math.ceil(x / float(n)) + # log('test_n: %d' % test_n) + res = [] + taken = [] + rest = l + for _i in range(0, n): + curr_test, curr_rest = list_take_drop(rest, test_n) + curr_train = taken + curr_rest + res.append((curr_train, curr_test)) + taken = taken + curr_test + rest = curr_rest + return res + +def train_test_NxCV_regr(max_feat, ntrees, crit, nprocs, msl, max_features, + max_samples, all_lines, cv_folds): + truth = [] + preds = [] + fold = 0 + train_tests = list_split(all_lines, cv_folds) + for train_set, test_set in train_tests: + X_train, y_train = read_AP_lines_regr(max_feat, train_set) + model = train_regr(ntrees, crit, nprocs, msl, max_features, + max_samples, X_train, y_train) + X_test, y_ref = read_AP_lines_regr(max_feat, test_set) + truth = truth + y_ref + y_preds = test(model, X_test) + y_preds_lst = [] + for y in y_preds: + y_preds_lst.append(y) + r2 = r2_score(y_ref, y_preds_lst) + rmse = root_mean_squared_error(y_ref, y_preds_lst) + log('fold: %d R2: %f RMSE: %f' % (fold, r2, rmse)) + preds = preds + y_preds_lst + fold += 1 + return (truth, preds) + +def train_test_NxCV_class(elastic_net, + max_feat, ntrees, nprocs, msl, max_features, + all_lines, cv_folds): + truth = [] + preds = [] + fold = 0 + train_tests = list_split(all_lines, cv_folds) + for train_set, test_set in train_tests: + _names, X_train, y_train = read_AP_lines_class(max_feat, train_set) + model = None + if elastic_net: + model = train_class_ElN(nprocs, + X_train, y_train) + else: + model = train_class_RFC(ntrees, nprocs, msl, max_features, + X_train, y_train) + _names, X_test, y_ref = read_AP_lines_class(max_feat, test_set) + truth = truth + y_ref + y_preds = test(model, X_test) + y_preds_lst = [] + for y in y_preds: + y_preds_lst.append(y) + auc = sklearn.metrics.roc_auc_score(y_ref, y_preds_lst) + mcc = sklearn.metrics.matthews_corrcoef(y_ref, y_preds_lst) + log('fold: %d AUC: %f MCC: %.3f' % (fold, auc, mcc)) + preds = preds + y_preds_lst + fold += 1 + return (truth, preds) + +def dump_pred_scores(output_fn, preds): + if output_fn != '': + with open(output_fn, 'w') as output: + for pred in preds: + print('%f' % pred, file=output) + +# a prediction is an integer class label, not a float +# FBR: TODO maybe output the active class proba as an additional column +def dump_pred_labels(output_fn, names, preds): + assert(len(names) == len(preds)) + if output_fn != '': + with open(output_fn, 'w') as output: + for name_pred in zip(names, preds): + print('%s\t%d' % name_pred, file=output) + +def gnuplot(title0, actual_values, predicted_values): + # escape underscores so that gnuplot doesn't interprete them + title = title0.replace('_', '\_') + xy_min = min(actual_values + predicted_values) + xy_max = max(actual_values + predicted_values) + _, commands_temp_fn = tempfile.mkstemp(prefix=""pcp_rfr_"", suffix="".gpl"") + commands_temp_file = open(commands_temp_fn, 'w') + _, data_temp_fn = tempfile.mkstemp(prefix=""pcp_rfr_"", suffix="".txt"") + data_temp_file = open(data_temp_fn, 'w') + gnuplot_commands = \ + [""set xlabel 'actual'"", + ""set ylabel 'predicted'"", + ""set xtics out nomirror"", + ""set ytics out nomirror"", + ""set xrange [%f:%f]"" % (xy_min, xy_max), + ""set yrange [%f:%f]"" % (xy_min, xy_max), + ""set key left"", + ""set size square"", + ""set title '%s'"" % title, + ""g(x) = x"", + ""f(x) = a*x + b"", + ""fit f(x) '%s' u 1:2 via a, b"" % data_temp_file.name, + ""plot g(x) t 'perfect' lc rgb 'black', \\"", + ""'%s' using 1:2 not, \\"" % data_temp_file.name, + ""f(x) t 'fit'""] + # dump gnuplot commands to temp file + for l in gnuplot_commands: + print(l, file=commands_temp_file) + commands_temp_file.close() + # dump data to temp file + for x, y in zip(actual_values, predicted_values): + print('%f %f' % (x, y), file=data_temp_file) + data_temp_file.close() + os.system(""gnuplot --persist %s"" % commands_temp_fn) + +def label_of_proba(p: float) -> int: + if p <= 0.5: + return 0 + else: + return 1 + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser(description = 'train/use a RFR model') + parser.add_argument('-i', + metavar = '', type = str, + dest = 'input_fn', + help = 'input data file') + parser.add_argument('-o', + metavar = '', type = str, + dest = 'output_fn', + default = '', + help = 'predictions output file') + parser.add_argument('--save', + metavar = '', type = str, + dest = 'model_output_fn', + default = '', + help = 'trained model output file') + parser.add_argument('--load', + metavar = '', type = str, + dest = 'model_input_fn', + default = '', + help = 'trained model input file') + parser.add_argument('-s', + metavar = '', type = int, + dest = 'rng_seed', + default = -1, + help = 'RNG seed') + parser.add_argument('-n', + metavar = '', type = int, + dest = 'ntrees', + default = 100, + help = 'number of trees') + parser.add_argument('--no-compress', + action = ""store_true"", + dest = 'no_compress', + default = False, + help = 'turn off saved model compression') + parser.add_argument('--no-plot', + action = ""store_true"", + dest = 'no_plot', + default = False, + help = 'turn off regression plot') + parser.add_argument('--eln', + action = ""store_true"", + dest = 'elastic_net', + default = False, + help = 'use ElasticNet instead of RFC (must be combined w/ --classif)') + parser.add_argument('-np', + metavar = '', type = int, + dest = 'nprocs', + default = 1, + help = 'max number of processes') + parser.add_argument('-msl', + metavar = '', type = int, + dest = 'msl', + default = 1, + help = 'min samples leaf') + parser.add_argument('-p', + metavar = '', type = float, + dest = 'train_p', + default = 0.8, + help = 'training set proportion') + parser.add_argument('-c', + metavar = '', type = str, + dest = 'criterion', + default = 'squared_error', + help = 'mae|squared_error') + parser.add_argument('--mtry', + metavar = '', type = float, + dest = 'train_feats', + default = 1.0, + help = 'float in ]0,1.0]') + parser.add_argument('-m', + metavar = '', type = int, + dest = 'max_feat', + default = 10_000, + help = 'max feature index (cf. AP dictionary)') + parser.add_argument('--NxCV', + metavar = '', type = int, + dest = 'cv_folds', + default = 1, + help = 'number of cross validation folds') + parser.add_argument('-ms', + metavar = '', type = float, + dest = 'max_samples', + # keep None here, not 1.0; reported sklearn bug + default = None, + help = 'max samples per bootstrap') + parser.add_argument('--classif', dest = 'classification', + action ='store_true', + default = False, + help = 'train a classifier \ + (default: train a regressor)') + # parse CLI --------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + model_input_fn = args.model_input_fn + model_output_fn = args.model_output_fn + abort_if(model_input_fn != '' and model_output_fn != '', + ""--load and --save are exclusive"") + rng_seed = args.rng_seed + if rng_seed != -1: + # only if the user asked for it, we make experiments repeatable + random.seed(rng_seed) + output_fn = args.output_fn + max_feat = args.max_feat # feat. dict related; _NOT_ model hyper param + # model's hyper parameters + cv_folds = args.cv_folds + assert(cv_folds >= 1) + msl = args.msl + crit = args.criterion + assert(crit in ['mae','squared_error']) + # REMARK: faster to train w/ squared_error, but better model with mae + ntrees = args.ntrees + abort_if(ntrees < 50, 'ntrees must be >= 50') + nprocs = args.nprocs + abort_if(nprocs < 1, 'nprocs must be >= 1') + train_p = args.train_p + if model_input_fn != '': + log('loading trained model: train_p <- 0.0') + train_p = 0.0 + if model_output_fn != '': + log('training prod model: train_p <- 1.0') + train_p = 1.0 + assert(0.0 <= train_p <= 1.0) + max_features = args.train_feats + assert(0.0 < max_features <= 1.0) + # FBR: TODO for classification and regression, the max_features defaults should not be the same + # IIRC for classif. this is sqrt(N); for regre. this is N + max_samples = args.max_samples # this one must default to None + if max_samples == 1.0: + max_samples = None # BUG in sklearn RFR probably; this forces 1.0 + no_compress = args.no_compress + no_plot = args.no_plot + elastic_net = args.elastic_net + classification = args.classification + regressor = not classification + # work --------------------------------------------------------- + # read in a .AP file w/ pIC50 values + all_lines = lines_of_file(input_fn) + if train_p > 0.0: + # if not using a model in production but train-testing: + # break any ordering the input file might have + random.shuffle(all_lines) + model = None + train_lines = [] + test_lines = [] + if cv_folds == 1: + train_lines, test_lines = train_test_split(train_p, all_lines) + if classification: + _names_train, X_train, y_train = \ + read_AP_lines_class(max_feat, train_lines) + names_test, X_test, y_test = \ + read_AP_lines_class(max_feat, test_lines) + if model_input_fn != '': + log('load model from %s' % model_input_fn) + model = joblib.load(model_input_fn) + else: + if elastic_net: + model = train_class_ElN(nprocs, + X_train, y_train) + else: + model = train_class_RFC(ntrees, nprocs, msl, max_features, + X_train, y_train) + if model_output_fn != '': + log('saving model to %s' % model_output_fn) + joblib.dump(model, model_output_fn, compress=('xz',9)) + # predict w/ trained model + if train_p < 1.0: + y_preds = test(model, X_test) + if elastic_net: # is a regressor, not a classifier + y_preds = list(map(label_of_proba, y_preds)) + dump_pred_labels(output_fn, names_test, y_preds) + # train_p = 0.0: we are in production, + # assume there are no labels + if train_p > 0.0: + auc = sklearn.metrics.roc_auc_score(y_test, y_preds) + mcc = sklearn.metrics.matthews_corrcoef(y_test, y_preds) + log('AUC: %.3f MCC: %.3f' % (auc, mcc)) + else: #regression + X_train, y_train = read_AP_lines_regr(max_feat, train_lines) + X_test, y_test = read_AP_lines_regr(max_feat, test_lines) + if model_input_fn != '': + log('loading model from %s' % model_input_fn) + model = joblib.load(model_input_fn) + else: + model = train_regr(ntrees, crit, nprocs, msl, max_features, + max_samples, X_train, y_train) + if model_output_fn != '': + log('saving model to %s' % model_output_fn) + if no_compress: + joblib.dump(model, model_output_fn, compress=False) + else: + joblib.dump(model, model_output_fn, compress=3) + # predict w/ trained model + if train_p < 1.0: + y_preds = test(model, X_test) + dump_pred_scores(output_fn, y_preds) + r2 = r2_score(y_test, y_preds) + rmse = root_mean_squared_error(y_test, y_preds) + if train_p > 0.0: + # train/test case + log('R2: %f RMSE: %f' % (r2, rmse)) + else: + # maybe production run or predictions + # on an external validation set + log('R2: %f RMSE: %f !!! ONLY VALID if test set had target values !!!' % (r2, rmse)) + else: + assert(cv_folds > 1) + if classification: + truth, preds = train_test_NxCV_class(elastic_net, + max_feat, ntrees, nprocs, msl, + max_features, all_lines, + cv_folds) + log('truths: %d preds: %d' % (len(truth), len(preds))) + auc = sklearn.metrics.roc_auc_score(truth, preds) + mcc = sklearn.metrics.matthews_corrcoef(truth, preds) + log('AUC: %.3f MCC: %.3f' % (auc, mcc)) + else: #regression + truth, preds = train_test_NxCV_regr(max_feat, ntrees, crit, + nprocs, msl, max_features, + max_samples, all_lines, + cv_folds) + log('truths: %d preds: %d' % (len(truth), len(preds))) + r2 = r2_score(truth, preds) + rmse = root_mean_squared_error(truth, preds) + r2_rmse = 'R2=%.3f RMSE=%.4f' % (r2, rmse) + log(r2_rmse) + title = '%s N=%d folds=%d mtry=%g %s' % (input_fn, ntrees, cv_folds, max_features, r2_rmse) + if not no_plot: + gnuplot(title, truth, preds) + after = time.time() + dt = after - before + log('dt: %.2f' % dt) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_smisur.py",".py","20799","532","#!/usr/bin/env python3 + +# Copyright (C) 2021, Francois Berenger +# Yamanishi laboratory, +# Department of Bioscience and Bioinformatics, +# Faculty of Computer Science and Systems Engineering, +# Kyushu Institute of Technology, +# 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan. + +# The Smiling Surgeon: fragment/assemble molecules + +import argparse +import ast +import molenc_common as common +import random +import rdkit +import sys +import time + +from molenc_common import RobustSmilesMolSupplier +from rdkit import Chem +from rdkit.Chem import Descriptors, Lipinski +from rdkit.Chem import RWMol +from rdkit.Chem.AtomPairs import Pairs + +def get_name(mol): + return mol.GetProp(""name"") + +def set_name(mol, name): + mol.SetProp(""name"", name) + +def index_for_atom_type(atom_types_dict, atom_type): + try: + return atom_types_dict[atom_type] + except KeyError: + # want indexes to start at 1; so the isotope number is + # always explicit in the fragments SMILES output + v = len(atom_types_dict) + 1 + atom_types_dict[atom_type] = v + return v + +def dict_reverse_binding(dico): + res = {} + for k, v in dico.items(): + res[v] = k + return res + +def fragment_on_bonds_and_label(mol, bonds): + labels = [] + atom_type_to_index = {} + for bi in bonds: + b = mol.GetBondWithIdx(bi) + i = b.GetBeginAtomIdx() + j = b.GetEndAtomIdx() + # get or create dictionary keys for those atom types + ai = mol.GetAtomWithIdx(i) + aj = mol.GetAtomWithIdx(j) + at_i = common.type_atom(ai) + at_j = common.type_atom(aj) + vi = index_for_atom_type(atom_type_to_index, at_i) + vj = index_for_atom_type(atom_type_to_index, at_j) + labels.append((vi, vj)) + fragmented = Chem.FragmentOnBonds(mol, bonds, dummyLabels=labels) + smi = Chem.MolToSmiles(fragmented) + name = get_name(mol) + index_to_atom_type = dict_reverse_binding(atom_type_to_index) + return (smi, name, index_to_atom_type) + +# SMILES fragmentation +def cut_some_bonds(frag_weight, mol, seed): + cuttable_bonds = common.find_cuttable_bonds(mol) + cut_bonds_indexes = [b.GetIdx() for b in cuttable_bonds] + total_weight = Descriptors.MolWt(mol) + nb_frags = round(total_weight / frag_weight) + max_cuts = min(len(cut_bonds_indexes), nb_frags - 1) + # print(""mol %s; cut %d bonds"" % (mol.GetProp(""name""), max_cuts), + # file=sys.stderr) + random.shuffle(cut_bonds_indexes) + to_cut = cut_bonds_indexes[0:max_cuts] + if len(to_cut) == 0: + # molecule too small: not fragmented + # still, we output it so that input and output SMILES files can be + # visualized side-by-side + smi = Chem.MolToSmiles(mol) + name = get_name(mol) + dico = {} + return (smi, name, dico) + else: + return fragment_on_bonds_and_label(mol, to_cut) + +def FragmentsSupplier(filename): + with open(filename) as f: + for line in f: + mixture, name = line.strip().split(""\t"") # enforce TAB-separated + fragments_smiles = mixture.split(""."") + parent_mol_name, dict_str = name.split("";"") + dico = ast.literal_eval(dict_str) + for i, smi in enumerate(fragments_smiles): + frag_name = '%s_f%d' % (parent_mol_name, i) + if len(dico) > 0: # molecule _was_ fragmented (not too small) + # print(smi, frag_name, dico, file=sys.stderr) # debug + yield (smi, frag_name, dico) + +def read_flat_fragments(flat_frags_fn): + res = [] + with open(flat_frags_fn) as f: + for line in f: + smi, name_dict = line.strip().split(""\t"") # enforce TAB-separated + name, dict_str = name_dict.split("";"") + dico = ast.literal_eval(dict_str) + if len(dico) > 0: # molecule _was_ fragmented (not too small) + res.append((smi, name, dico)) + return res + +def read_all_fragments(in_frags_fn, flat_frags_out_fn): + res = [] + with open(flat_frags_out_fn, 'w') as out: + for (smi, name, dico) in FragmentsSupplier(in_frags_fn): + res.append((smi, name, dico)) + out.write('%s\t%s;%s\n' % (smi, name, str(dico))) + return res + +def random_choose_one(all_frags): + n = len(all_frags) + i = random.randint(0, n - 1) + return all_frags[i] + +def count_uniq_fragment(all_frags): + ss = set() # string set + for (smi, _name, _dico) in all_frags: + ss.add(smi) + return len(ss) + +# the only one attached to a dummy atom / attachment point +def get_src_atom_idx(a): + neighbs = a.GetNeighbors() + assert(len(neighbs) == 1) + src_a = neighbs[0] + return src_a.GetIdx() + +# set ""name"" prop. to frag_mol +# record (frag_mol, src_atom_idx, src_atom_typ, dst_atom_typ) +def index_fragments(frags): + res = {} + for smi, frag_name, dico in frags: + frag_mol = Chem.MolFromSmiles(smi) + set_name(frag_mol, frag_name) + # process each attachment point + for a in frag_mol.GetAtoms(): + if a.GetAtomicNum() == 0: # '*' wildcard atom + isotope = a.GetIsotope() + # print(isotope, dico) # debug + dst_typ = dico[isotope] + dst_idx = a.GetIdx() + src_idx = get_src_atom_idx(a) + src_a = frag_mol.GetAtomWithIdx(src_idx) + src_typ = common.type_atom(src_a) + # record the fragment under key: (dst_typ, src_typ) + # i.e. ready to use by requiring fragment + key = (dst_typ, src_typ) + # print('insert key: %s' % str(key)) # debug + value = (frag_mol, dst_idx) + a.SetProp(""dst_typ"", dst_typ) + a.SetProp(""src_typ"", src_typ) + try: + previous_frags = res[key] + previous_frags.append(value) + except KeyError: + res[key] = [value] + return res + +# extract fragments from values of the dictionary +def extract_fragments(dico): + res = [] + for _k, v in dico.items(): + for (frag_mol, _dst_idx) in v: + res.append(frag_mol) + return res + +# return a new molecule, where m1 and m2 are now attached +# via a single bond; after this bond is introduced, the former +# corresponding attachment points/atoms are removed +def bind_molecules(m1, m2, dst_idx, idx2): + # print('m1: %s' % Chem.MolToSmiles(m1)) #debug + # print('m2: %s' % Chem.MolToSmiles(m2)) #debug + n1 = m1.GetNumAtoms() + n2 = m2.GetNumAtoms() + m = n1 + n2 + rw_mol = Chem.RWMol(Chem.CombineMols(m1, m2)) + assert(rw_mol.GetNumAtoms() == m) + name1 = get_name(m1) + name2 = get_name(m2) + new_name = '%s|%s' % (name1, name2) + set_name(rw_mol, new_name) + ai = rw_mol.GetAtomWithIdx(dst_idx) + assert(ai.GetAtomicNum() == 0) # attachment point + dst_typ = ai.GetProp(""dst_typ"") + src_idx = get_src_atom_idx(ai) + src_typ = ai.GetProp(""src_typ"") + dst_idx2 = n1 + idx2 + aj = rw_mol.GetAtomWithIdx(dst_idx2) + assert(aj.GetAtomicNum() == 0) # attachment point + dst_typ2 = aj.GetProp(""dst_typ"") + src_idx2 = get_src_atom_idx(aj) + src_typ2 = aj.GetProp(""src_typ"") + if (dst_typ == src_typ2 and + src_typ == dst_typ2): + # attach. points are compatible + rw_mol.AddBond(src_idx, src_idx2, Chem.rdchem.BondType.SINGLE) + # remove former attachment points + rw_mol.RemoveAtom(dst_idx2) # to not shift lower atom indexes + rw_mol.RemoveAtom(dst_idx) + return rw_mol + else: + # attach. points are incompatible !!! + print(""bind_molecules: could not connect fragment %s w/ %s"" % + (name1, name2), file=sys.stderr) + assert(False) + +# first attach. point/atom index, or -1 if no more +def find_first_attach_index(mol): + for a in mol.GetAtoms(): + if a.GetAtomicNum() == 0: # '*' wildcard atom + return a.GetIdx() + return -1 + +class TooManyFrags(Exception): + """"""Max number of fragments was reached"""""" + pass + +# attach matching fragments until no attachment points are left +def grow_fragment(seed_frag_mol, frags_index): + # safeguard: if we are building a molecule with more than + # 50 fragments, something is obviously wrong somewhere + max_frags = 50 + frag_seed_mol = seed_frag_mol + dst_idx = find_first_attach_index(frag_seed_mol) + i = 0 + while ((dst_idx != -1) and (i < max_frags)): + dst_a = frag_seed_mol.GetAtomWithIdx(dst_idx) + dst_typ = dst_a.GetProp(""dst_typ"") + src_typ = dst_a.GetProp(""src_typ"") + # draw compatible fragment + key = (src_typ, dst_typ) # current to wanted direction + # print('want key: %s' % str(key)) # debug + possible_compat_frags = frags_index[key] + compat_frag = random_choose_one(possible_compat_frags) + (frag_mol2, dst_idx2) = compat_frag + dst_a2 = frag_mol2.GetAtomWithIdx(dst_idx2) + dst_typ2 = dst_a2.GetProp(""dst_typ"") + src_typ2 = dst_a2.GetProp(""src_typ"") + # check fragments compatibility + assert(src_typ == dst_typ2) + assert(dst_typ == src_typ2) + # connect them + frag_seed_mol = bind_molecules(frag_seed_mol, frag_mol2, + dst_idx, dst_idx2) + dst_idx = find_first_attach_index(frag_seed_mol) + i += 1 + if i == max_frags: + raise TooManyFrags + try: + Chem.SanitizeMol(frag_seed_mol) + # the constituting fragments might have some stereo info + # that we want to preserve up to the final molecule + # ! MANDATORY _AFTER_ SanitizeMol ! + Chem.AssignStereochemistry(frag_seed_mol) + # print('after sanitize then stereo: %s' % Chem.MolToSmiles(res_mol), + # file=sys.stderr) + return frag_seed_mol.GetMol() + except rdkit.Chem.rdchem.KekulizeException: + print(""KekulizeException in %s"" % get_name(frag_seed_mol), + file=sys.stderr) + return frag_seed_mol.GetMol() + +def write_out(gen_mol, count, gen_smi, output): + frag_names = get_name(gen_mol) + name_prfx = 'genmol%d' % count + print(""%s\t%s:%s"" % (gen_smi, name_prfx, frag_names), file=output) + +# Oprea's lead-like filter +# Hann, M. M., & Oprea, T. I. (2004). +# Pursuing the leadlikeness concept in pharmaceutical research. +# Current opinion in chemical biology, 8(3), 255-263. +def lead_like_filter(mol): + # MolW <= 460 + if Descriptors.MolWt(mol) > 460: + return False + # -4.0 <= LogP <= 4.2 + LogP = Descriptors.MolLogP(mol) + if LogP < -4.0 or LogP > 4.2: + return False + # # LogSw >= -5 # ignored + # rotB <= 10 + if Descriptors.NumRotatableBonds(mol) > 10: + return False + # nRings <= 4 (number of SSSR rings, _not_ aromatic rings) + if Chem.GetSSSR(mol) > 4: + return False + # HBD <= 5 + if Descriptors.NumHDonors(mol) > 5: + return False + # HBA <= 9 + if Descriptors.NumHAcceptors(mol) > 9: + return False + return True # lead-like then! + +def new_enough(filter_diverse, gen_smi, seen_smiles): + if not filter_diverse: + return True + else: + if not (gen_smi in seen_smiles): + seen_smiles.add(gen_smi) + return True + else: + return False + +def lead_like_enough(ll_filter, mol): + return ((not ll_filter) or lead_like_filter(mol)) + +# Tran-Nguyen, V. K., Jacquemard, C., & Rognan, D. (2020). +# LIT-PCBA: An unbiased data set for machine learning and virtual screening. +# Journal of chemical information and modeling, 60(9), 4263-4273. +def drug_like_filter(mol): + MolW = Descriptors.MolWt(mol) + if MolW <= 150 or MolW >= 800: # 150 < MolW < 800 Da + return False + cLogP = Descriptors.MolLogP(mol) + if cLogP <= -3.0 or cLogP >= 5.0: # −3.0 < AlogP < 5.0 + return False + RotB = Descriptors.NumRotatableBonds(mol) + if RotB >= 15: # RotB < 15 + return False + HBA = Descriptors.NumHAcceptors(mol) + if HBA >= 10: # HBA < 10 + return False + HBD = Descriptors.NumHDonors(mol) + if HBD >= 10: # HBD < 10 + return False + FC = Chem.rdmolops.GetFormalCharge(mol) + if FC <= -2 or FC >= 2: # −2.0 < FC < 2.0 + return False + return True # Still here? Drug-like then! + +def drug_like_enough(dl_filter, mol): + return ((not dl_filter) or drug_like_filter(mol)) + +# Lisurek, M., Rupp, B., Wichard, J., Neuenschwander, M., von Kries, J. P., +# Frank, R., ... & Kühne, R. (2010). +# Design of chemical libraries with potentially bioactive molecules applying +# a maximum common substructure concept. Molecular diversity, 14(2), 401-408. +# SMARTS patterns kindly provided by Michael Lisurek +pat1 = Chem.MolFromSmarts('[C,c]S(=O)(=O)[F,Cl,Br,I]') # sulfonylhalide +pat2 = Chem.MolFromSmarts('[C,c]S(=O)(=O)O[CX4]') # sulfone_ester +pat3 = Chem.MolFromSmarts('C(=O)[F,Cl,Br,I]') # acylhalide +pat4 = Chem.MolFromSmarts('O=COC=O') # acidanhydride +pat5 = Chem.MolFromSmarts('c1([F,Cl,Br,I])ncccn1') # 2-halo_pyrimidine +pat6 = Chem.MolFromSmarts('[H]C=O') # aldehyde +pat7 = Chem.MolFromSmarts('C(=O)C(=O)') # 1,2-dicarbonyl +pat8 = Chem.MolFromSmarts('C1OC1') # epoxide +pat9 = Chem.MolFromSmarts('C1NC1') # aziridine +pat10 = Chem.MolFromSmarts('C(=O)S') # thioester +pat11 = Chem.MolFromSmarts('[#7]!@[#7]') # hydrazine +pat12 = Chem.MolFromSmarts('C=[CH2]') # ethenes +pat13 = Chem.MolFromSmarts('[H,*,!N][N;!R]=[C;!R]([*,H])[*,H]') # imine +pat14 = Chem.MolFromSmarts('[CX4]I') # alkyl_iodide +pat15 = Chem.MolFromSmarts('[Se]') # selenide +pat16 = Chem.MolFromSmarts('O-O') # peroxide +pat17 = Chem.MolFromSmarts('[NX3]!@[OX2]') # hetero-hetero_single_bond +pat18 = Chem.MolFromSmarts('[NX3]!@[NX3]') # hetero-hetero_single_bond +pat19 = Chem.MolFromSmarts('[NX3]!@[SX2]') # hetero-hetero_single_bond +pat20 = Chem.MolFromSmarts('[SX2]!@[SX2]') # hetero-hetero_single_bond +pat21 = Chem.MolFromSmarts('[SX2]!@[OX2]') # hetero-hetero_single_bond + +def stable_filter(mol): + if (mol.HasSubstructMatch(pat1) or + mol.HasSubstructMatch(pat2) or + mol.HasSubstructMatch(pat3) or + mol.HasSubstructMatch(pat4) or + mol.HasSubstructMatch(pat5) or + mol.HasSubstructMatch(pat6) or + mol.HasSubstructMatch(pat7) or + mol.HasSubstructMatch(pat8) or + mol.HasSubstructMatch(pat9) or + mol.HasSubstructMatch(pat10) or + mol.HasSubstructMatch(pat11) or + mol.HasSubstructMatch(pat12) or + mol.HasSubstructMatch(pat13) or + mol.HasSubstructMatch(pat14) or + mol.HasSubstructMatch(pat15) or + mol.HasSubstructMatch(pat16) or + mol.HasSubstructMatch(pat17) or + mol.HasSubstructMatch(pat18) or + mol.HasSubstructMatch(pat19) or + mol.HasSubstructMatch(pat20) or + mol.HasSubstructMatch(pat21)): + return False + else: + return True + +def stable_enough(s_filter, mol): + return ((not s_filter) or stable_filter(mol)) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""fragment molecules, or assemble molecular fragments"") + parser.add_argument(""-i"", metavar = ""input.smi"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.smi"", dest = ""output_fn"", + help = ""output file"") + parser.add_argument(""--frag-dump"", metavar = ""frags_dump.smi"", + dest = ""flat_frags_out_fn"", + help = ""flat fragments dump file"", + default = None) + parser.add_argument(""--seed"", dest = ""seed"", default = -1, + type = int, help = ""RNG seed"") + parser.add_argument(""-n"", dest = ""nb_passes"", default = 1, + type = int, help = ""number of fragmentation passes"") + parser.add_argument(""--assemble"", dest = ""nmols"", default = -1, + type = int, help = ""number of molecules to generate"") + parser.add_argument(""--diverse"", dest = ""diverse"", default = False, + action = ""store_true"", + help = ""enforce uniqueness of generated SMILES"") + parser.add_argument(""--lead-like"", dest = ""ll_filter"", default = False, + action = ""store_true"", + help = ""only generate lead-like molecules"") + parser.add_argument(""--drug-like"", dest = ""dl_filter"", default = False, + action = ""store_true"", + help = ""only generate drug-like molecules"") + parser.add_argument(""--stable"", dest = ""s_filter"", default = False, + action = ""store_true"", + help = ""only generate stable molecules"") + # 150 Da: D. Rognan's suggested max fragment weight + parser.add_argument(""-w"", dest = ""frag_weight"", default = 150.0, + type = float, help = ""fragment weight (default=150Da)"") + # parse CLI + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + flat_frags_out_fn = args.flat_frags_out_fn + nb_passes = args.nb_passes + nmols = args.nmols + assemble = nmols > 0 + rng_seed = args.seed + diverse = args.diverse + ll_filter = args.ll_filter + dl_filter = args.dl_filter + s_filter = args.s_filter + frag_w = args.frag_weight + seen_smiles = set() + if rng_seed != -1: + # only if the user asked for it, we make experiments repeatable + random.seed(rng_seed) + output = open(args.output_fn, 'w') + drug_filter_fails = 0 + lead_filter_fails = 0 + stable_filter_fails = 0 + not_new_fails = 0 + count = 0 + grow_frag_errors = 0 + if assemble: # assembling fragments --------------------------------------- + smi_fragments = read_all_fragments(input_fn, ""/dev/null"") + nb_uniq = count_uniq_fragment(smi_fragments) + print('read %d fragments (uniq: %d)' % (len(smi_fragments), nb_uniq)) + index = index_fragments(smi_fragments) + fragments = extract_fragments(index) + print('%d fragment keys' % len(index)) + # # inspect the index (to debug) + # for k, v in index.items(): + # print(""k:%s -> %d frags"" % (k, len(v))) + while count < nmols: + # FBR: parallelize here + seed_frag = random_choose_one(fragments) + # print('seed_frag: %s' % get_name(seed_frag)) # debug + try: + gen_mol = grow_fragment(seed_frag, index) + gen_smi = Chem.MolToSmiles(gen_mol) + is_new = new_enough(diverse, gen_smi, seen_smiles) + if not is_new: + not_new_fails += 1 + is_lead_like = lead_like_enough(ll_filter, gen_mol) + if not is_lead_like: + lead_filter_fails += 1 + is_drug_like = drug_like_enough(dl_filter, gen_mol) + if not is_drug_like: + drug_filter_fails += 1 + is_stable = stable_enough(s_filter, gen_mol) + if not is_stable: + stable_filter_fails += 1 + if is_new and is_lead_like and is_drug_like and is_stable: + write_out(gen_mol, count, gen_smi, output) + count += 1 + except TooManyFrags: + print(""TooManyFrags from %s"" % get_name(seed_frag), + file=sys.stderr) + except KeyError: + # FBR: this means I should correct something somewhere + grow_frag_errors += 1 + else: + # fragmenting --------------------------------------------------------- + mol_supplier = RobustSmilesMolSupplier(input_fn) + for name, mol in mol_supplier: + for i in range(nb_passes): + fragments_smi, parent_name, dico = \ + cut_some_bonds(frag_w, mol, rng_seed) + print(""%s\t%s_p%d;%s"" % + (fragments_smi, name, i, str(dico)), file=output) + count += 1 + after = time.time() + dt = after - before + if assemble: + print(""generated %d molecules at %.2f mol/s (%d errors)"" % + (count, count / dt, grow_frag_errors), file=sys.stderr) + # log failures + print(""Fails: drug: %d lead: %d stable: %d new: %d"" % + (drug_filter_fails, + lead_filter_fails, + stable_filter_fails, + not_new_fails)) + else: + print(""read %d molecules at %.2f mol/s"" % + (count, count / dt), file=sys.stderr) + output.close() + if flat_frags_out_fn != None: + # read all fragments back and store them in a ""flat"" format + _smi_fragments = read_all_fragments(args.output_fn, flat_frags_out_fn) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_mol2smi.py",".py","3575","99","#!/usr/bin/env python3 + +# Copyright (C) 2020, Francois Berenger +# Yamanishi laboratory, +# Department of Bioscience and Bioinformatics, +# Faculty of Computer Science and Systems Engineering, +# Kyushu Institute of Technology, +# 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan. + +# txt molecule to SMILES + +import argparse, rdkit, re, sys, time +import molenc_common as common +from rdkit import Chem + +# create a fake molecule for the corresp. fragment +def read_one_molecule(input): + res_mol = Chem.RWMol() + atoms_header = input.readline().strip() + if atoms_header == '': + raise common.End_of_file # no EOF in Python... + nb_atoms, name = common.read_atoms_header(atoms_header) + old2new = {} + for _i in range(nb_atoms): + line = input.readline().strip() + (index, nb_pi, atomic_num, nb_HA, charge, stereo) = \ + common.read_atom(line) + # add atom + a = Chem.Atom(atomic_num) + a.SetFormalCharge(charge) + if stereo > 0: # set chirality + a.SetChiralTag(common.atom_stereo_code_to_chiral_tag(stereo)) + j = res_mol.AddAtom(a) + # we need to convert atom indexes + old2new[index] = j + bonds_header = input.readline().strip() + nb_bonds = common.read_bonds_header(bonds_header) + stereo_bonds = [] + for i in range(nb_bonds): + line = input.readline().strip() + (start_i, bt, stop_i, (stereo, c, d)) = common.read_bond(line) + start = old2new[start_i] + stop = old2new[stop_i] + # add bond + n = res_mol.AddBond(start, stop, bt) + if stereo != rdkit.Chem.rdchem.BondStereo.STEREONONE: + bi = n - 1 + # convert stereo bond stereo atoms indexes + a = old2new[c] + b = old2new[d] + stereo_bonds.append((bi, stereo, a, b)) + # all atoms and bonds are here now + # so stereo bonds info can be set + for (bi, stereo, a, b) in stereo_bonds: + bond = res_mol.GetBondWithIdx(bi) + bond.SetStereo(stereo) + bond.SetStereoAtoms(a, b) + print('%s stereo %s on bond %d (%d, %d)' % + (name, common.char_of_bond_stereo(stereo), bi, a, b), + file=sys.stderr) + try: + Chem.SanitizeMol(res_mol) + Chem.AssignStereochemistry(res_mol) # ! MANDATORY; AFTER SanitizeMol ! + except rdkit.Chem.rdchem.KekulizeException: + print(""KekulizeException in %s"" % name, file=sys.stderr) + smi = Chem.MolToSmiles(res_mol) + return (smi, name) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser(description = ""txt molecule to smi"") + parser.add_argument(""-i"", metavar = ""input.mols"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.smi"", dest = ""output_fn"", + help = ""output file"") + # parse CLI + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output = open(args.output_fn, 'w') + count = 0 + with open(input_fn) as input: + try: + while True: + smi, name = read_one_molecule(input) + count += 1 + print('%s\t%s' % (smi, name), file=output) + except common.End_of_file: + pass + after = time.time() + dt = after - before + print(""%d molecules at %.2f molecule/s"" % + (count, count / dt), file=sys.stderr) + output.close() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_regr_stats.py",".py","691","28","#!/usr/bin/env python3 +# +# output R2 and RMSE regression statistics from a file containing pairs +# of float values (one blank-separated pair per line; no header) + +import sklearn, sys + +from sklearn.metrics import r2_score, root_mean_squared_error + +def read_pair(line): + tokens = line.strip().split() + x = float(tokens[0]) + y = float(tokens[1]) + xy = (x, y) + return xy + +if __name__ == '__main__': + input_fn = sys.argv[1] + xs = [] + ys = [] + for line in open(input_fn).readlines(): + x, y = read_pair(line) + xs.append(x) + ys.append(y) + r2 = r2_score(xs, ys) + rmse = root_mean_squared_error(xs, ys) + print('R2=%.3f RMSE=%.3f' % (r2, rmse)) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_not_peptide.py",".py","802","34","#!/usr/bin/env python3 +# +# only output molecules w/o three consecutive peptide bonds +# molecules not filtered out are written to stdout +# usage: molenc_not_peptide.py INPUT.smi + +import rdkit +from rdkit import Chem +import sys + +input_fn = sys.argv[1] + +total = 0 +peptides = 0 +errors = 0 + +three_pep_bonds = Chem.MolFromSmiles('NCC(=O)NCC(=O)NCC(=O)') + +for line in open(input_fn).readlines(): + smi = line.strip().split()[0] + mol = Chem.MolFromSmiles(smi) + if mol: + if mol.HasSubstructMatch(three_pep_bonds): + peptides += 1 + else: + print(line, end='') + else: + print('ERROR: could not parse: %s' % line, file=sys.stderr) + errors += 1 + total += 1 + +print('INFO: errors/peptides/total=%d/%d/%d' % (errors, peptides, total), + file=sys.stderr) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_gpr.py",".py","14826","399","#!/usr/bin/env python3 + +# Copyright (C) 2024, Francois Berenger +# Tsuda laboratory, Graduate School of Frontier Sciences, +# The University of Tokyo, Japan. +# +# Gaussian Process Regressor CLI wrapper +# input file must have three columns; tab-separated; +# line format: SMILES\tMOLNAME\tpIC50 + +import argparse +import joblib # type: ignore +import math +import numpy as np +import os +import random +import rdkit +import sklearn # type: ignore +import sys +import tempfile +import time + +from rdkit import Chem, DataStructs +from rdkit.Chem import rdFingerprintGenerator +#from sklearn.metrics import mean_squared_error, r2_score # type: ignore +from sklearn.metrics import root_mean_squared_error, r2_score # type: ignore +from sklearn.gaussian_process.kernels import PairwiseKernel # type: ignore +from sklearn.gaussian_process import GaussianProcessRegressor # type: ignore + +# # sklearn.metrics.root_mean_squared_error +# def root_mean_squared_error(y_true, y_pred): +# return mean_squared_error(y_true, y_pred, squared=False) + +# FBR: TODO NxCV should really be parallelized... + +# original code for the GPR from +# https://github.com/MobleyLab/active-learning-notebooks/blob/main/MultiobjectiveAL.ipynb +# refactored by Francois Berenger + +def hour_min_sec(): + tm = time.localtime() + return (tm.tm_hour, tm.tm_min, tm.tm_sec) + +# use this instead of print to log on stderr +def log(*args, **kwargs): + hms = hour_min_sec() + print('%02d:%02d:%02d ' % hms, file=sys.stderr, end='') + return print(*args, **kwargs, file=sys.stderr) + +def abort_if(cond, err_msg): + if cond: + log(""%s"", err_msg) + sys.exit(1) + +def lines_of_file(fn): + with open(fn) as input: + return list(map(str.strip, input.readlines())) + +def train_test_split(train_portion, lines): + n = len(lines) + train_n = math.ceil(train_portion * n) + test_n = n - train_n + log('train/test: %d/%d' % (train_n, test_n)) + train = lines[0:train_n] + test = lines[train_n:] + assert(len(train) + len(test) == n) + return (train, test) + +def gpr_test(model, X_test): + preds = model.predict(X_test, return_std=False) + return preds + +# production predictions; w/ stddev +def gpr_pred(model, X_test): + # (preds, vars) + return model.predict(X_test, return_std=True) + +def list_take_drop(l, n): + took = l[0:n] + dropped = l[n:] + return (took, dropped) + +# cut list into several lists +def list_split(l, n): + x = float(len(l)) + test_n = math.ceil(x / float(n)) + # log('test_n: %d' % test_n) + res = [] + taken = [] + rest = l + for _i in range(0, n): + curr_test, curr_rest = list_take_drop(rest, test_n) + curr_train = taken + curr_rest + res.append((curr_train, curr_test)) + taken = taken + curr_test + rest = curr_rest + return res + +def parse_smiles_line(line: str) -> tuple[str, str, float]: + # print(""DEBUG: %s"" % line) + split = line.strip().split() + smi = split[0] + name = split[1] + pIC50 = 0.0 # default value + if len(split) == 3: + pIC50 = float(split[2]) + return (smi, name, pIC50) + +def parse_smiles_lines(lines: list[str]) -> tuple[list[rdkit.Chem.rdchem.Mol], + list[str], + list[float]]: + mols = [] + names = [] + pIC50s = [] + for line in lines: + smi, name, pIC50 = parse_smiles_line(line) + mol = Chem.MolFromSmiles(smi) + if mol != None: + mols.append(mol) + names.append(name) + pIC50s.append(pIC50) + else: + log(""ERROR: molenc_gpr.py: parse_smiles_lines: could not parse smi for %s: %s"" % \ + (name, smi)) + return (mols, names, pIC50s) + +def dump_pred_scores(output_fn, names, preds): + if output_fn != '': + with open(output_fn, 'w') as output: + for name, pred in zip(names, preds): + print('%s\t%f' % (name, pred), file=output) + +def dump_pred_vars(output_fn, names, preds, stddevs): + if output_fn != '': + with open(output_fn, 'w') as output: + for name, pred, std in zip(names, preds, stddevs): + print('%s\t%f\t%f' % (name, pred, std), file=output) + +def gnuplot(title0, actual_values, predicted_values): + # escape underscores so that gnuplot doesn't interprete them + title = title0.replace('_', '\\_') + all_vals = actual_values + predicted_values + xy_min = min(all_vals) + xy_max = max(all_vals) + _, commands_temp_fn = tempfile.mkstemp(prefix=""gpr_"", suffix="".gpl"") + commands_temp_file = open(commands_temp_fn, 'w') + _, data_temp_fn = tempfile.mkstemp(prefix=""gpr_"", suffix="".txt"") + data_temp_file = open(data_temp_fn, 'w') + gnuplot_commands = \ + [""set xlabel 'actual'"", + ""set ylabel 'predicted'"", + ""set xtics out nomirror"", + ""set ytics out nomirror"", + ""set xrange [%f:%f]"" % (xy_min, xy_max), + ""set yrange [%f:%f]"" % (xy_min, xy_max), + ""set key left"", + ""set size square"", + ""set title '%s'"" % title, + ""g(x) = x"", + ""f(x) = a*x + b"", + ""fit f(x) '%s' u 1:2 via a, b"" % data_temp_file.name, + ""plot g(x) t 'perfect' lc rgb 'black', \\"", + ""'%s' using 1:2 not, \\"" % data_temp_file.name, + ""f(x) t 'fit'""] + # dump gnuplot commands to temp file + for l in gnuplot_commands: + print(l, file=commands_temp_file) + commands_temp_file.close() + # dump data to temp file + for x, y in zip(actual_values, predicted_values): + print('%f %f' % (x, y), file=data_temp_file) + data_temp_file.close() + os.system(""gnuplot --persist %s"" % commands_temp_fn) + +# global parameter +stereo_sensitive = False + +def ecfpX_of_mol(mol: rdkit.Chem.rdchem.Mol, radius) -> np.ndarray: + generator = \ + rdFingerprintGenerator.GetMorganGenerator( + radius, fpSize=2048, includeChirality=stereo_sensitive) + fp = generator.GetFingerprint(mol) + arr = np.zeros((1,), int) + DataStructs.ConvertToNumpyArray(fp, arr) + # arr: np.ndarray of int64 w/ length 2048 + return arr + +def counted_atom_pairs_of_mol(mol): + generator = rdFingerprintGenerator.GetAtomPairGenerator(fpSize=8192, countSimulation=True) + fp = generator.GetFingerprint(mol) + arr = np.zeros((1,), int) + DataStructs.ConvertToNumpyArray(fp, arr) + return arr + +def ecfp4_of_mol(mol): + return ecfpX_of_mol(mol, 2) + +# parse SMILES, ignore names, read pIC50s then encode molecules w/ ECFP4 2048b +# return (X_train, y_train) +def read_SMILES_lines_regr(lines, use_CAP): + mols, names, pIC50s = parse_smiles_lines(lines) + X_train = None + if use_CAP: + X_train = np.array([counted_atom_pairs_of_mol(mol) for mol in mols]) + else: + X_train = np.array([ecfp4_of_mol(mol) for mol in mols]) + y_train = np.array(pIC50s) + return (X_train, names, y_train) + +def tanimoto_opt(a: np.ndarray, b: np.ndarray, **kwargs) -> float: + # assume inputs are 0/1 arrays + a = a.astype(np.uint8, copy=False) + b = b.astype(np.uint8, copy=False) + inter = np.dot(a, b) + union = a.sum() + b.sum() - inter + if union != 0: + return (inter / union) + else: + return 0.0 + +def gpr_train(X_train, y_train): + model = GaussianProcessRegressor(kernel=PairwiseKernel(metric=tanimoto_opt), normalize_y=True) + model.fit(X_train, y_train) + return model + +def gpr_train_test_NxCV(all_lines, cv_folds, use_CAP): + truth = [] + preds = [] + fold = 0 + train_tests = list_split(all_lines, cv_folds) + for train_set, test_set in train_tests: + X_train, _names_train, y_train = read_SMILES_lines_regr(train_set, use_CAP) + X_test, _names_test, y_ref = read_SMILES_lines_regr(test_set, use_CAP) + model = gpr_train(X_train, y_train) + truth = truth + list(y_ref) + y_preds = gpr_test(model, X_test) + y_preds_lst = list(y_preds) + r2 = r2_score(y_ref, y_preds_lst) + rmse = root_mean_squared_error(y_ref, y_preds_lst) + log('fold: %d R2: %f RMSE: %f' % (fold, r2, rmse)) + preds = preds + y_preds_lst + fold += 1 + return (truth, preds) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser(description = 'train/use a GPR model') + parser.add_argument('-i', + metavar = '', type = str, + dest = 'input_fn', + help = 'input data file') + parser.add_argument('-o', + metavar = '', type = str, + dest = 'output_fn', + default = '', + help = 'predictions output file') + parser.add_argument('--save', + metavar = '', type = str, + dest = 'model_output_fn', + default = '', + help = 'trained model output file') + parser.add_argument('--load', + metavar = '', type = str, + dest = 'model_input_fn', + default = '', + help = 'trained model input file') + parser.add_argument('-s', + metavar = '', type = int, + dest = 'rng_seed', + default = -1, + help = 'RNG seed') + parser.add_argument('--no-compress', + action = ""store_true"", + dest = 'no_compress', + default = False, + help = 'turn off saved model compression') + parser.add_argument('--CAP', + action = ""store_true"", + dest = 'use_CAP', + default = False, + help = 'use counted atom pairs instead of ECFP4') + parser.add_argument('--no-plot', + action = ""store_true"", + dest = 'no_plot', + default = False, + help = 'turn off gnuplot') + parser.add_argument('-np', + metavar = '', type = int, + dest = 'nprocs', + default = 1, + help = 'max number of processes') + parser.add_argument('-p', + metavar = '', type = float, + dest = 'train_p', + default = 0.8, + help = 'training set proportion') + parser.add_argument('--NxCV', + metavar = '', type = int, + dest = 'cv_folds', + default = 1, + help = 'number of cross validation folds') + parser.add_argument('--stereo', + action = ""store_true"", + dest = 'stereo_sensitive', + default = False, + help = 'make the fingerprint stereo-sensitive') + # parse CLI --------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + model_input_fn = args.model_input_fn + model_output_fn = args.model_output_fn + stereo_sensitive = args.stereo_sensitive # global var + abort_if(model_input_fn != '' and model_output_fn != '', + ""--load and --save are exclusive"") + rng_seed = args.rng_seed + if rng_seed != -1: + # only if the user asked for it, we make experiments repeatable + random.seed(rng_seed) + output_fn = args.output_fn + cv_folds = args.cv_folds + assert(cv_folds >= 1) + nprocs = args.nprocs + abort_if(nprocs < 1, 'nprocs must be >= 1') + train_p = args.train_p + if model_input_fn != '': + log('loading trained model: train_p <- 0.0') + train_p = 0.0 + if model_output_fn != '': + log('training prod model: train_p <- 1.0') + train_p = 1.0 + assert(0.0 <= train_p <= 1.0) + no_compress = args.no_compress + no_plot = args.no_plot + use_CAP = args.use_CAP + # work --------------------------------------------------------- + # read input + all_lines = lines_of_file(input_fn) + if train_p > 0.0: + # if not using a model in production but train-testing: + # break any ordering the input file might have + if rng_seed == -1: + log('WARN: all_lines shuffled w/o rng_seed (not reproducible)') + random.shuffle(all_lines) + model = None + train_lines = [] + test_lines = [] + if cv_folds == 1: + train_lines, test_lines = train_test_split(train_p, all_lines) + X_train, _names_train, y_train = read_SMILES_lines_regr(train_lines, use_CAP) + X_test, names_test, y_test = read_SMILES_lines_regr(test_lines, use_CAP) + if model_input_fn != '': + log('loading model from %s' % model_input_fn) + model = joblib.load(model_input_fn) + else: + model = gpr_train(X_train, y_train) + if model_output_fn != '': + log('saving model to %s' % model_output_fn) + if no_compress: + joblib.dump(model, model_output_fn, compress=False) + else: + joblib.dump(model, model_output_fn, compress=3) + # predict w/ trained model + if train_p == 0.0: + # production use + y_preds, y_vars = gpr_pred(model, X_test) + dump_pred_vars(output_fn, names_test, y_preds, y_vars) + elif train_p < 1.0: + y_preds = gpr_test(model, X_test) + dump_pred_scores(output_fn, names_test, y_preds) + r2 = r2_score(y_test, y_preds) + rmse = root_mean_squared_error(y_test, y_preds) + if train_p > 0.0: + # train/test case + log('R2: %.3f RMSE: %.3f fn: %s' % (r2, rmse, input_fn)) + else: + # maybe production run or predictions + # on an external validation set + log('R2: %.3f RMSE: %.3f fn: %s !!! ONLY VALID if test set had target values !!!' % + (r2, rmse, input_fn)) + else: + assert(cv_folds > 1) + truth, preds = gpr_train_test_NxCV(all_lines, cv_folds, use_CAP) + log('truths: %d preds: %d' % (len(truth), len(preds))) + r2 = r2_score(truth, preds) + rmse = root_mean_squared_error(truth, preds) + r2_rmse = 'GPR R2=%.3f RMSE=%.3f fn=%s' % (r2, rmse, input_fn) + log(r2_rmse) + if no_plot == False: + title = '%s folds=%d %s' % (input_fn, cv_folds, r2_rmse) + gnuplot(title, truth, preds) + after = time.time() + dt = after - before + log('dt: %.2f' % dt) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_std.py",".py","5822","149","#!/usr/bin/env python3 +# +# Copyright (C) 2022, Francois Berenger +# Tsuda laboratory, Tokyo University, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# CLI wrapper for rdkit's standardizer + +import argparse, re, sys, time +from multiprocessing import Pool +from rdkit import Chem +#from rdkit.Chem.MolStandardize import Standardizer # rdkit.version <= '2023.09.3' +#standardizer = Standardizer() +from rdkit.Chem.MolStandardize import rdMolStandardize # rdkit.version >= '2024.03.5' + +regex = re.compile('\\s') + +def find_whitespace(s): + m = re.search(regex, s) + if m == None: + return -1 + else: + return m.start() + +def parse_smiles_line(line): + fst_white = find_whitespace(line) + smi = '' + name = '' + if fst_white == -1: + # no whitespace separator: assume molecule has no name + # use the SMILES itself as the name, so this unnamed + # molecule will percolate instead instead of behing lost + smi = line + name = line + else: + smi = line[0:fst_white] + name = line[fst_white + 1:] + mol = Chem.MolFromSmiles(smi) + return (mol, name) + +# # for rdkit.version == '2023.09.3' +# def standardize(preserve_stereo, preserve_taut, mol): +# if preserve_stereo or preserve_taut: +# s_mol = standardizer.standardize(mol) +# # We don't need to get fragment parent, because the charge parent is the largest fragment +# s_mol = standardizer.charge_parent(s_mol, skip_standardize=True) +# s_mol = standardizer.isotope_parent(s_mol, skip_standardize=True) +# if not preserve_stereo: +# s_mol = standardizer.stereo_parent(s_mol, skip_standardize=True) +# if not preserve_taut: +# s_mol = standardizer.tautomer_parent(s_mol, skip_standardize=True) +# return standardizer.standardize(s_mol) +# else: +# # standardizer.super_parent(mol): _NOT_ standardizer.standardize(mol) +# # which doesn't even unsalt the molecule... +# return standardizer.super_parent(mol) + +# for rdkit.version == '2024.03.5' +def standardize(preserve_stereo, preserve_taut, mol): + if preserve_stereo or preserve_taut: + # We don't need to get fragment parent, because the charge parent is the largest fragment + s_mol = rdMolStandardize.ChargeParent(mol, skipStandardize=False) + s_mol = rdMolStandardize.IsotopeParent(s_mol, skipStandardize=True) + if not preserve_stereo: + s_mol = rdMolStandardize.StereoParent(s_mol, skipStandardize=False) + if not preserve_taut: + s_mol = rdMolStandardize.TautomerParent(s_mol, skipStandardize=False) + return s_mol + else: + return rdMolStandardize.SuperParent(mol, skipStandardize=False) + +def process(line): + errors = 0 + count = 0 + res = """" + stripped = line.strip() + mol, name = parse_smiles_line(stripped) + if mol == None: + errors += 1 + else: + try: + std = standardize(preserve_stereo, preserve_taut, mol) + smi_std = Chem.MolToSmiles(std) + res = ""%s\t%s\n"" % (smi_std, name) + count += 1 + except Exception: + print(""exception: %s"" % name, file=sys.stderr) + errors += 1 + return (errors, count, res) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser(description = ""rdkit's standardizer"") + parser.add_argument(""-i"", metavar = ""input.smi"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output_std.smi"", dest = ""output_fn"", + help = ""molecules output file"") + parser.add_argument('-s', dest='preserve_stereo', + action='store_true', default=False, + help = ""preserve stereo chemistry"") + parser.add_argument('-t', dest='preserve_tautomer', + action='store_true', default=False, + help = ""preserve tautomer \ +(i.e. skip tautomer standardization)"") + parser.add_argument(""-n"", metavar = ""nprocs"", dest = ""nprocs"", + type = int, default = 1, + help = ""number of processors for parallelization (default=%(default)s)"") + parser.add_argument(""-c"", metavar = ""chunk_size"", dest = ""csize"", + type = int, default = 50, + help = ""chunk size for parallelization (default=%(default)s)"") + # parse CLI --------------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output_fn = args.output_fn + preserve_stereo = args.preserve_stereo + preserve_taut = args.preserve_tautomer + nprocs = args.nprocs + csize = args.csize + # parse CLI end ----------------------------------------------------------- + count = 0 + errors = 0 + pool = None + if nprocs > 1: + pool = Pool(nprocs) + with open(output_fn, 'w') as out: + with open(input_fn, 'r') as input: + if pool is not None: + for e, c, res in pool.imap(process, input, csize): + errors += e + count += c + if len(res) > 0: + out.write(""%s"" % res) + else: + for line in input.readlines(): + e, c, res = process(line) + errors += e + count += c + if len(res) > 0: + out.write(""%s"" % res) + after = time.time() + dt = after - before + print(""%d molecules @ %.2fHz; %d errors"" % (count, count / dt, errors), + file=sys.stderr) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_smi2png.py",".py","642","24","#!/usr/bin/env python3 + +import rdkit, sys +from rdkit import Chem +from rdkit.Chem import Draw + +input_smi = sys.argv[1] +output_png = sys.argv[2] + +# WARNING: only read and consider first line of input SMILES file +with open(input_smi, 'r') as input: + with open(output_png, 'wb') as output: + line = input.readline() + line.strip() + split = line.split() + smi = split[0] + name = split[1] + mol = Chem.MolFromSmiles(smi) + assert(mol != None) + d2d = Draw.MolDraw2DCairo(-1,-1) + Draw.DrawMoleculeACS1996(d2d, mol, legend=name) + pix = d2d.GetDrawingText() + output.write(pix) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_linker.py",".py","1087","37","#!/usr/bin/env python3 + +import rdkit, typing +from rdkit import Chem +from rdkit.Chem import AllChem + +def create_PEG_chain(length: int): + s = '' + for i in range(length): + s += '[CH2R0X4][CH2R0X4][OH0R0X2]' # SMARTS for one PEG unit + #return s + return Chem.MolFromSmarts(s) + +# assume longest linker is 10 units of PEG +peg10 = create_PEG_chain(10) +peg09 = create_PEG_chain(9) +peg08 = create_PEG_chain(8) +peg07 = create_PEG_chain(7) +peg06 = create_PEG_chain(6) +peg05 = create_PEG_chain(5) +peg04 = create_PEG_chain(4) +peg03 = create_PEG_chain(3) +peg02 = create_PEG_chain(2) +#peg01: I assume a single PEG unit is too short to be a proper linker + +peg_10_downto_2 = [peg10, peg09, peg08, peg07, peg06, peg05, peg04, peg03, peg02] + +# remove the PEG linker, if any +# if not, the molecule is returned unchanged (either it has no linker, or +# the linker is not PEG) +def cut_PEG_linker(mol): + for patt in peg_10_downto_2: + if mol.HasSubstructMatch(patt): + res = AllChem.DeleteSubstructs(mol, patt) + return (True, res) + return (False, mol) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_lean.py",".py","4788","136","#!/usr/bin/env python3 + +# Copyright (C) 2020, Francois Berenger +# Yamanishi laboratory, +# Department of Bioscience and Bioinformatics, +# Faculty of Computer Science and Systems Engineering, +# Kyushu Institute of Technology, +# 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan. + +# Short: tool to automatically find the necessary/minimal training set size + +# Long: find the size of the random partition from the training set that is +# enough to train a model (can help avoiding overfitting, since we might not +# need to use the whole training set to tune the model). +# However, note that for production you will still need to train your +# model on the full training set. +# In effect, we check that the distribution of the variable to model does not +# significantly change by adding more training samples. +# Usually, with a smaller dataset, you can get a model faster and hence +# accelerate your computational experiments. +# +# Bibliography: +# ============= +# Domingos, P. (2012). +# ""A few useful things to know about machine learning."" +# Communications of the ACM, 55(10), 78-87. + +import argparse, random, scipy, sys +import numpy as np +from scipy import stats + +stderr = sys.stderr + +def lines_of_file(fn): + with open(fn) as f: + return f.readlines() + +def get_field(sep_char, field, line): + tokens = line.split(sep = sep_char) + value_str = tokens[field - 1] + return float(value_str) + +def get_all_values(sep_char, field, lines): + res = [] + for l in lines: + value = get_field(sep_char, field, l) + res.append(value) + return res + +# ANSI terminal colors for UNIX +black = ""\033[30m"" +red = ""\033[31m"" +green = ""\033[32m"" +yellow = ""\033[33m"" +blue = ""\033[34m"" +magenta = ""\033[35m"" +cyan = ""\033[36m"" +white = ""\033[37m"" +color_reset = ""\033[39m"" + +def dichotomic_search(all_values, good_vals, low, curr, high): + smaller_sample = np.random.choice(all_values, size = curr, replace = False) + ks, p_val = stats.ks_2samp(smaller_sample, all_values, + alternative='two-sided', mode='auto') + if p_val > 0.95: + # recurse lower + # print(""%sbig_enough: %d"" % (green, curr)) + good_vals.append(curr) + curr_next = round((low + curr) / 2) + if curr_next != curr: + dichotomic_search(all_values, good_vals, low, curr_next, curr) + else: + return + else: + # recurse bigger + # print(""%stoo small: %d"" % (white, curr)) + curr_next = round((curr + high) / 2) + if curr_next != curr: + dichotomic_search(all_values, good_vals, curr, curr_next, high) + else: + return + +def main(): + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""automatically determine minimal training set size"") + parser.add_argument(""-i"", metavar = ""INPUT_FILE"", dest = ""input_fn"", + help = ""line-oriented file containing the \ + target variable (training-set)"", type = str) + parser.add_argument(""-d"", metavar = ""DELIM_CHAR"", dest = ""sep_char"", + help = ""field delimiter char (default=\\t)"", + default = '\t', type = str) + parser.add_argument(""-f"", metavar = ""FIELD_NUM"", dest = ""field"", + help = ""target variable field number (starts at 1)"", + default = 1, type = int) + parser.add_argument(""-n"", metavar = ""REPEATS"", dest = ""repeats"", + help = ""statistical test repeats (default=50)"", + default = 50, type = int) + # parse CLI + args = parser.parse_args() + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(file = stderr) + sys.exit(1) + input_fn = args.input_fn + sep_char = args.sep_char + field = args.field + repeats = args.repeats + if field == -1: + print(""-f is mandatory"", file = stderr) + exit(1) + # compute default params + all_lines = lines_of_file(input_fn) + nb_lines = len(all_lines) + # replace all lines by the values of interest + all_values = get_all_values(sep_char, field, all_lines) + # show some stats to the user for troubleshooting + mini = np.min(all_values) + aveg = np.average(all_values) + stdv = np.std(all_values) + maxi = np.max(all_values) + print(""min,avg+/-std,max: %.3f,%.3f+/-%.3f,%.3f"" % + (mini, aveg, stdv, maxi)) + acc = [] + for i in range(repeats): + good_vals = [] + dichotomic_search(all_values, good_vals, 0, round(nb_lines / 2), nb_lines) + best = min(good_vals) + print(""smallest: %d"" % best) + acc.append(best) + upper_bound = max(acc) + print(""REQUIRED: %d"" % upper_bound) + +if __name__ == '__main__': + main() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_scan.sh",".sh","899","39","#!/bin/bash + +#set -x # DEBUG + +# check params +if [ ""$#"" -ne 3 ]; then + # 0 1 2 3 + echo ""usage: molenc.sh input.smi output.txt features.dix"" + exit 1 +fi + +input=$1 +output=$2 +dico=$3 + +std_log=$input'.std_log' +tmp=`mktemp` +tmp_smi=$tmp'_std.smi' +tmp_scan=$tmp'_scan.smi' +tmp_types=$tmp'_std.types' +tmp_enc=$tmp'_std.enc' + +# tell user how to install standardiser if not here +which standardiser 2>&1 > /dev/null || \ + echo 'ERROR: type: pip3 install chemo-standardizer' + +echo standardizing molecules... +(standardiser -i $input -o $tmp_smi 2>&1) > $std_log +echo wildcard scan... +molenc_scan.py $tmp_smi > $tmp_scan +echo typing atoms... +molenc_type_atoms.py $tmp_scan > $tmp_types +echo encoding molecules... +molenc_e -i $tmp_types -r 0:1 -o $tmp_enc +molenc_d -i $tmp_enc -o $output -d $dico + +# cleanup +rm -f $std_log $tmp $tmp_smi $tmp_scan $tmp_types $tmp_enc +","Shell" +"QSAR","UnixJunkie/molenc","bin/csv2txt.sh",".sh","193","8","#!/bin/bash + +# csv format output by molenc_lizard.py to txt format expected by +# several molenc tools + +awk -F',' \ + '{print $1"",""$2"",[0:""$3"";1:""$4"";2:""$5"";3:""$6"";4:""$7"";5:""$8"";6:""$9""]""}' $1 +","Shell" +"QSAR","UnixJunkie/molenc","bin/smi2svg.py",".py","1362","45","#!/usr/bin/env python3 + +# One 2D picture SVG for each SMILES line +# molecule images are named after the index of the molecule in the input file +# they are created in the current directory + +import argparse +import rdkit +import sys +from rdkit import Chem +from rdkit.Chem import AllChem +from rdkit.Chem.Draw import rdMolDraw2D + +def RobustMolSupplier(filename): + with open(filename) as f: + i = 0 + for line in f: + words = line.split() + index = i + i += 1 + smi = words[0] + name = words[1] + yield (index, name, Chem.MolFromSmiles(smi)) + +if __name__ == '__main__': + # parse CLI + # show help in case user has no clue of what to do + if len(sys.argv) != 2: + sys.stderr.write(""usage: %s input.smi\n"" % sys.argv[0]) + sys.exit(1) + input_smi = sys.argv[1] + for i, name, mol in RobustMolSupplier(input_smi): + if mol is None: + continue + AllChem.Compute2DCoords(mol) # generate 2D conformer + d = rdMolDraw2D.MolDraw2DSVG(200, 200) + # d.drawOptions().addAtomIndices = True + caption = '%d %s' % (i, name) + d.DrawMolecule(mol, legend = caption) + d.FinishDrawing() + out_fn = '%d.svg' % i + print('creating %s' % out_fn) + with open(out_fn, 'w') as out: + out.write(d.GetDrawingText()) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_eln.py",".py","5671","181","#!/usr/bin/env python3 + +# Copyright (C) 2024, Francois Berenger +# Tsuda laboratory, Graduate School of Frontier Sciences, +# The University of Tokyo, Japan. +# +# Random Forests Regressor or Classifier (RFR or RFC) CLI wrapper + +import argparse +import math +import os +import random +import scipy +import sklearn +import sys +import tempfile +import time +import typing +import joblib + +from sklearn.linear_model import ElasticNet, ElasticNetCV +from sklearn.metrics import r2_score, root_mean_squared_error +from scipy import sparse + +def hour_min_sec(): + tm = time.localtime() + return (tm.tm_hour, tm.tm_min, tm.tm_sec) + +# use this instead of print to log on stderr +def log(*args, **kwargs): + hms = hour_min_sec() + print('%02d:%02d:%02d ' % hms, file=sys.stderr, end='') + return print(*args, **kwargs, file=sys.stderr) + +def abort_if(cond, err_msg): + if cond: + log(""%s"", err_msg) + sys.exit(1) + +def count_lines_of_file(fn): + count = 0 + with open(fn) as input: + for _l in input: + count += 1 + return count + +def lines_of_file(fn): + with open(fn) as input: + return list(map(str.strip, input.readlines())) + +# current training-set line format example: +# mol_0,0.0,[1:23;8:3;22:2;45:6;56:1] +def split_AP_line(line): + fields = line.split(',') + name = str(fields[0]) + pIC50 = float(fields[1]) + feat_val_strings = fields[2] + return (name, pIC50, feat_val_strings) + +def read_features(row, col, data, i, max_feat_idx, feat_vals_str): + # print('feat_vals: %d' % (len(feat_vals))) + feat_vals = feat_vals_str.strip('[]') + for feat_val in feat_vals.split(';'): + feat_str, val_str = feat_val.split(':') + feat = int(feat_str) + val = float(val_str) + # print('%d:%d' % (feat, val)) + # assert(feat <= max_feat_idx) + if feat > max_feat_idx: + print(""molenc_rfr.py: read_features: \ +feat > max_feat_idx: %d > %d"" % (feat, max_feat_idx), + file=sys.stderr) + sys.exit(1) + if val != 0.0: + row.append(i) + col.append(feat) + data.append(val) + +def read_AP_lines_regr(max_feature_index, lines): + nb_lines = len(lines) + pIC50s = [] + row = [] + col = [] + data = [] + for i, line in enumerate(lines): + _name, pIC50, features_str = split_AP_line(line) + # log('%d %f' % (i, pIC50)) + pIC50s.append(pIC50) + read_features(row, col, data, i, max_feature_index, features_str) + X = sparse.csr_matrix((data, (row, col)), + shape=(nb_lines, max_feature_index + 1)) + log('read_AP_lines_regr: (%d,%d)' % (X.shape[0], X.shape[1])) + return (X, pIC50s) + +def train_test_split(train_portion, lines): + n = len(lines) + train_n = math.ceil(train_portion * n) + test_n = n - train_n + log('train/test: %d/%d' % (train_n, test_n)) + train = lines[0:train_n] + test = lines[train_n:] + assert(len(train) + len(test) == n) + return (train, test) + +def train_ElN_regr(nprocs, X_train, y_train): + log('ElasticNet regr. training...') + model = ElasticNetCV(cv=5, n_jobs=nprocs, random_state=314159265, + selection='random') + # model = ElasticNet(alpha=0.004517461806329454, l1_ratio=0.5, random_state=314159265, + # selection='random') + model.fit(X_train, y_train) + # e.g. alpha=0.004517461806329454 l1_ratio=0.5 + log('ElasticNet: alpha=%f l1_ratio=%f' % (model.alpha_, model.l1_ratio_)) + return model + +def test(model, X_test): + return model.predict(X_test) + +def list_take_drop(l, n): + took = l[0:n] + dropped = l[n:] + return (took, dropped) + +# cut list into several lists +def list_split(l, n): + x = float(len(l)) + test_n = math.ceil(x / float(n)) + # log('test_n: %d' % test_n) + res = [] + taken = [] + rest = l + for _i in range(0, n): + curr_test, curr_rest = list_take_drop(rest, test_n) + curr_train = taken + curr_rest + res.append((curr_train, curr_test)) + taken = taken + curr_test + rest = curr_rest + return res + +def train_test_NxCV_regr(nprocs, max_features, all_lines, cv_folds): + truth = [] + preds = [] + fold = 0 + train_tests = list_split(all_lines, cv_folds) + for train_set, test_set in train_tests: + X_train, y_train = read_AP_lines_regr(max_feat, train_set) + model = train_regr(ntrees, crit, nprocs, msl, max_features, + max_samples, X_train, y_train) + X_test, y_ref = read_AP_lines_regr(max_feat, test_set) + truth = truth + y_ref + y_preds = test(model, X_test) + y_preds_lst = [] + for y in y_preds: + y_preds_lst.append(y) + r2 = r2_score(y_ref, y_preds_lst) + rmse = root_mean_squared_error(y_ref, y_preds_lst) + log('fold: %d R2: %f RMSE: %f' % (fold, r2, rmse)) + preds = preds + y_preds_lst + fold += 1 + return (truth, preds) + +if __name__ == '__main__': + before = time.time() + train_fn = sys.argv[1] + test_fn = sys.argv[2] + max_feat = int(sys.argv[3]) + train_lines = lines_of_file(train_fn) + test_lines = lines_of_file(test_fn) + X_train, y_train = read_AP_lines_regr(max_feat, train_lines) + X_test, y_test = read_AP_lines_regr(max_feat, test_lines) + model = train_ElN_regr(1, X_train, y_train) + preds = test(model, X_test) + log('truths: %d preds: %d' % (len(y_test), len(preds))) + r2 = r2_score(y_test, preds) + rmse = root_mean_squared_error(y_test, preds) + r2_rmse = '%s %s R2=%.3f RMSE=%.4f' % (train_fn, test_fn, r2, rmse) + log(r2_rmse) + after = time.time() + dt = after - before + log('dt: %.2f' % dt) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_frag.py",".py","5754","161","#!/usr/bin/env python3 + +# Copyright (C) 2020, Francois Berenger +# Yamanishi laboratory, +# Department of Bioscience and Bioinformatics, +# Faculty of Computer Science and Systems Engineering, +# Kyushu Institute of Technology, +# 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan. + +# atom typing and molecule fragmentation hints + +import argparse +import molenc_common as common +import rdkit +import sys +import time + +from molenc_common import RobustSmilesMolSupplier +from rdkit import Chem +from rdkit.Chem import Descriptors +from rdkit.Chem.Draw import rdMolDraw2D +from molenc_common import StereoCodes + +to_stereo_code = \ + { # atom.SetChiralTag(Chem.ChiralType.CHI_UNSPECIFIED) + '?': StereoCodes.ANY_CENTER, + # SMILES @@ means clockwise / R / Chem.ChiralType.CHI_TETRAHEDRAL_CW + 'R': StereoCodes.R_CENTER, + # SMILES @ means anti clockwise / S / Chem.ChiralType.CHI_TETRAHEDRAL_CCW + 'S': StereoCodes.S_CENTER, + rdkit.Chem.rdchem.BondStereo.STEREONONE: StereoCodes.NONE, + rdkit.Chem.rdchem.BondStereo.STEREOANY: StereoCodes.ANY_BOND, + rdkit.Chem.rdchem.BondStereo.STEREOZ: StereoCodes.Z_BOND, + rdkit.Chem.rdchem.BondStereo.STEREOE: StereoCodes.E_BOND, + rdkit.Chem.rdchem.BondStereo.STEREOCIS: StereoCodes.CIS_BOND, + rdkit.Chem.rdchem.BondStereo.STEREOTRANS: StereoCodes.TRANS_BOND } + +def get_atom_stereo_codes(m): + # by default, each atom has no stereo + res = [StereoCodes.NONE for i in range(m.GetNumAtoms())] + # # unless detected otherwise for stereo bonds + # for b in m.GetBonds(): + # bstereo = b.GetStereo() + # if bstereo != rdkit.Chem.rdchem.BondStereo.STEREONONE: + # i = b.GetBeginAtomIdx() + # j = b.GetEndAtomIdx() + # k = to_stereo_code[bstereo] + # res[i] = k + # res[j] = k + # or for chiral centers + for i, k in Chem.FindMolChiralCenters(m): + res[i] = to_stereo_code[k] + return res + +# # stereo code tests +# cis = Chem.MolFromSmiles('C/C=C\C') +# trans = Chem.MolFromSmiles('C/C=C/C') +# l_ala = Chem.MolFromSmiles('N[C@@H](C)C(=O)O') +# d_ala = Chem.MolFromSmiles('N[C@H](C)C(=O)O') +# print(get_stereo_codes(cis)) +# print(get_stereo_codes(trans)) +# print(get_stereo_codes(l_ala)) +# print(get_stereo_codes(d_ala)) + +def print_typed_atoms(out, mol): + stereo = get_atom_stereo_codes(mol) + for a in mol.GetAtoms(): + i = a.GetIdx() + t = common.type_atom(a) + s = stereo[i] + print(""%d %s,%d"" % (i, t, s), file=out) + +def char_of_bond_type(bond): + t = bond.GetBondType() + if t == rdkit.Chem.rdchem.BondType.SINGLE: + return '-' + elif t == rdkit.Chem.rdchem.BondType.AROMATIC: + return ':' + elif t == rdkit.Chem.rdchem.BondType.DOUBLE: + return '=' + elif t == rdkit.Chem.rdchem.BondType.TRIPLE: + return '#' + else: + assert(""molenc_frag.py: char_of_bond_type"" == """") + +def string_of_bond_stereo(bond): + st = bond.GetStereo() + c = common.char_of_bond_stereo(st) + if c == 'N': + return c + else: + (a, b) = bond.GetStereoAtoms() + str = ""%c:%d:%d"" % (c, a, b) + return str + +# print all bonds with their type (and optional stereo info) +def print_bonds(out, mol): + print(""#bonds:%d"" % mol.GetNumBonds(), file=out) + bonds = mol.GetBonds() + for bond in bonds: + a = bond.GetBeginAtomIdx() + b = bond.GetEndAtomIdx() + t = char_of_bond_type(bond) + stereo = string_of_bond_stereo(bond) + print(""%d %c %d %s"" % (a, t, b, stereo), file=out) + +# print which bonds are cuttable and the suggested number of cuts +def print_cuttable_bonds(out, mol): + cuttable_bonds = common.find_cuttable_bonds(mol) + total_weight = Descriptors.MolWt(mol) + # 150 Da: D. Rognan's suggested max fragment weight + nb_frags = round(total_weight / 150) + max_cuts = min(len(cuttable_bonds), nb_frags - 1) + print(""#cut_bonds:%d:%d"" % (len(cuttable_bonds), max_cuts), file=out) + for bond in cuttable_bonds: + i = bond.GetIdx() + print(""%d"" % i, file=out) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""compute molecule fragmentation hints"") + parser.add_argument(""-i"", metavar = ""input.smi"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.txt"", dest = ""output_fn"", + help = ""output file"") + parser.add_argument(""--draw"", dest = ""draw_mol"", action ='store_true', + default = False, + help = ""output PNG for each molecule w/ atom indexes"") + # parse CLI + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + draw_mol = args.draw_mol + output = open(args.output_fn, 'w') + count = 0 + # fragmenting --------------------------------------------------------- + mol_supplier = RobustSmilesMolSupplier(input_fn) + for name, mol in mol_supplier: + print(""#atoms:%d %s"" % (mol.GetNumAtoms(), name), file=output) + print_typed_atoms(output, mol) + print_bonds(output, mol) + print_cuttable_bonds(output, mol) + count += 1 + if draw_mol: + d = rdMolDraw2D.MolDraw2DCairo(500, 500) + d.drawOptions().addAtomIndices = True + d.DrawMolecule(mol) + d.FinishDrawing() + png_fn = '%s.png' % name + with open(png_fn, 'wb') as fn: + fn.write(d.GetDrawingText()) + after = time.time() + dt = after - before + print(""%d molecules at %.2f mol/s"" % (count, count / dt), file=sys.stderr) + output.close() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_atoms_filter.py",".py","2766","82","#!/usr/bin/env python3 +# +# Copyright (C) 2023, Francois Berenger +# Tsuda laboratory, Tokyo University, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# Keep only molecules using allowed atoms + +import argparse, re, sys, time +from rdkit import Chem + +regex = re.compile('\s') + +def find_whitespace(s): + m = re.search(regex, s) + if m == None: + return -1 + else: + return m.start() + +def parse_smiles_line(line): + fst_white = find_whitespace(line) + smi = '' + name = '' + if fst_white == -1: + # no whitespace separator: assume molecule has no name + # use the SMILES itself as the name, so this unnamed + # molecule will percolate instead of behing lost + smi = line + name = line + else: + smi = line[0:fst_white] + name = line[fst_white + 1:] + return Chem.MolFromSmiles(smi) + +def parse_atoms_list(line): + return set(line.strip().split(',')) + +def atoms_filter(allowed_atoms, mol): + for a in mol.GetAtoms(): + if a.GetSymbol() not in allowed_atoms: + return False + return True + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser(description = ""filter out molecules w/ disallowed atoms"") + parser.add_argument(""-i"", metavar = ""input.smi"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.smi"", dest = ""output_fn"", + help = ""molecules output file"") + parser.add_argument('-a', metavar = ""ATOMS_LIST"", dest='allowed_atoms', + default=""C,H,N,O,P,S,F,Cl,Br,I"", + help = ""comma-separated list of allowed atoms \ + (default=C,H,N,O,P,S,F,Cl,Br,I)"") + # parse CLI --------------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output_fn = args.output_fn + allowed_atoms = parse_atoms_list(args.allowed_atoms) + # parse CLI end ----------------------------------------------------------- + count = 0 + errors = 0 + with open(output_fn, 'w') as out: + with open(input_fn, 'r') as input: + for line in input.readlines(): + mol = parse_smiles_line(line.strip()) + if atoms_filter(allowed_atoms, mol): + out.write(""%s"" % line) + else: + errors += 1 + count += 1 + after = time.time() + dt = after - before + print(""%d molecules @ %.2fHz; removed %d"" % (count, count / dt, errors), + file=sys.stderr) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_get_names.sh",".sh","621","27","#!/bin/bash +# +# extract molecule names from properly formated SDF files to stdout +# usage: ./molenc_get_names.sh 1.sdf 2.sdf 3.sdf ... + +set -u + +function get_sdf_names () { + (echo '$$$$'; cat $1) | \ + \egrep --no-group-separator -A1 '^\$\$\$\$$' | \egrep -v '^\$\$\$\$$' +} + +for fn in ""$@""; do + case ""$fn"" in + *.sdf.gz) + zcat $fn | get_sdf_names /dev/stdin + ;; + *.sdf) + get_sdf_names $fn + ;; + *) # unknown option + echo ""molenc_get_names.sh: unsupported file format: ""$fn >> /dev/stderr + exit 1 + ;; + esac +done +","Shell" +"QSAR","UnixJunkie/molenc","bin/molenc_HA.py",".py","880","29","#!/usr/bin/env python3 + +# Copyright (C) 2023, Francois Berenger +# Tsuda laboratory, The University of Tokyo, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. + +# Robust Heavy Atom count from a .smi input file +# (molenc_lizard.py can ignore some molecules because of RDKit) + +import rdkit, sys +from rdkit import Chem +from rdkit.Chem import Lipinski + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for i, line in enumerate(f): + words = line.split() + smile = words[0] + name = words[1] + yield (Chem.MolFromSmiles(smile, sanitize=False), name) + +input_smi = sys.argv[1] +for mol, name in RobustSmilesMolSupplier(input_smi): + if mol is None: + print(""rdkit could not parse: %s"" % name, file=sys.stderr) + else: + HA = Lipinski.HeavyAtomCount(mol) + print(""%s\t%d"" % (name, HA)) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_ifg.py",".py","3400","97","#!/usr/bin/env python3 + +# Original authors: Richard Hall and Guillaume Godin +# This file is part of the RDKit. +# The contents are covered by the terms of the BSD license +# which is included in the file license.txt, found at the root +# of the RDKit source tree. + +# Richard hall 2017 +# IFG main code +# Guillaume Godin 2017 +# refine output function +# astex_ifg: identify functional groups a la Ertl, J. Cheminform (2017) 9:36 +from rdkit import Chem +from collections import namedtuple +import sys + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + words = line.split() + smile = words[0] + name = "" "".join(words[1:]) # everything after the SMILES string + yield (name, Chem.MolFromSmiles(smile)) + +def merge(mol, marked, aset): + bset = set() + for idx in aset: + atom = mol.GetAtomWithIdx(idx) + for nbr in atom.GetNeighbors(): + jdx = nbr.GetIdx() + if jdx in marked: + marked.remove(jdx) + bset.add(jdx) + if not bset: + return + merge(mol, marked, bset) + aset.update(bset) + +# atoms connected by non-aromatic double or triple bond to any heteroatom +# c=O should not match (see fig1, box 15). I think using A instead of * should sort that out? +PATT_DOUBLE_TRIPLE = Chem.MolFromSmarts('A=,#[!#6]') +# atoms in non aromatic carbon-carbon double or triple bonds +PATT_CC_DOUBLE_TRIPLE = Chem.MolFromSmarts('C=,#C') +# acetal carbons, i.e. sp3 carbons connected to tow or more oxygens, nitrogens or sulfurs; these O, N or S atoms must have only single bonds +PATT_ACETAL = Chem.MolFromSmarts('[CX4](-[O,N,S])-[O,N,S]') +# all atoms in oxirane, aziridine and thiirane rings +PATT_OXIRANE_ETC = Chem.MolFromSmarts('[O,N,S]1CC1') + +PATT_TUPLE = (PATT_DOUBLE_TRIPLE, PATT_CC_DOUBLE_TRIPLE, PATT_ACETAL, PATT_OXIRANE_ETC) + +def identify_functional_groups(mol): + marked = set() +#mark all heteroatoms in a molecule, including halogens + for atom in mol.GetAtoms(): + if atom.GetAtomicNum() not in (6,1): # would we ever have hydrogen? + marked.add(atom.GetIdx()) + +#mark the four specific types of carbon atom + for patt in PATT_TUPLE: + for path in mol.GetSubstructMatches(patt): + for atomindex in path: + marked.add(atomindex) + +#merge all connected marked atoms to a single FG + groups = [] + while marked: + grp = set([marked.pop()]) + merge(mol, marked, grp) + groups.append(grp) + +#extract also connected unmarked carbon atoms + ifg = namedtuple('IFG', ['atomIds', 'atoms', 'type']) + ifgs = [] + for g in groups: + uca = set() + for atomidx in g: + for n in mol.GetAtomWithIdx(atomidx).GetNeighbors(): + if n.GetAtomicNum() == 6: + uca.add(n.GetIdx()) + ifgs.append(ifg(atomIds=tuple(list(g)), atoms=Chem.MolFragmentToSmiles(mol, g, canonical=True), type=Chem.MolFragmentToSmiles(mol, g.union(uca),canonical=True))) + return ifgs + +def main(): + argc = len(sys.argv) + if argc == 1: + print('usage: ifg.py input.smi', file=sys.stderr) + exit(1) + input_fn = sys.argv[1] + for name, mol in RobustSmilesMolSupplier(input_fn): + fgs = identify_functional_groups(mol) + nb_fun_groups = len(fgs) + print(""%s %d"" % (name, nb_fun_groups)) + +if __name__ == ""__main__"": + main() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_deepsmi.py",".py","3669","103","#!/usr/bin/env python3 + +# Copyright (C) 2021, Francois Berenger +# Tsuda laboratory, Tokyo University, Japan. + +# DeepSMILES encoder/decoder from/to SMILES +# +# ""DeepSMILES: An adaptation of SMILES for use in machine-learning of +# chemical structures"". Noel M. O’Boyle and Andrew Dalke. ChemRxiv (2018). + +import argparse +import deepsmiles +import molenc_common +import rdkit +import sys +import time + +from rdkit import Chem +from rdkit.Chem import AllChem + +from molenc_common import RobustSmilesSupplier + +def encode(converter, smi): + return converter.encode(smi) + +def decode(converter, deep_smi): + try: + smi = converter.decode(deep_smi) + # currently, de decoder does not output a canonical SMILES + # https://github.com/baoilleach/deepsmiles/issues/19 + # I want canonical SMILES, because this is rdkit's default + mol = Chem.MolFromSmiles(smi) + cano_smi = Chem.MolToSmiles(mol) + return cano_smi + except deepsmiles.DecodeError as e: + print(""molenc_deepsmi.py: decode: '%s'"" % e.message, + file = sys.stderr) + return None + +if __name__ == '__main__': + before = time.time() + # CLI options + parser = argparse.ArgumentParser( + description = ""DeepSMILES encoder/decoder"") + parser.add_argument(""-i"", metavar = ""input.smi"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.smi"", dest = ""output_fn"", + help = ""molecules output file"") + parser.add_argument(""--no-rings"", dest = ""rings"", + action = ""store_true"", + default = False, + help = ""DeepSMILES without ring openings"") + parser.add_argument(""--no-branches"", dest = ""branches"", + action = ""store_true"", + default = False, + help = ""DeepSMILES without branches"") + parser.add_argument(""-e"", dest = ""do_encode"", + action = ""store_true"", + default = True, + help = ""encode: SMILES to DeepSMILES (default)"") + parser.add_argument(""-d"", dest = ""do_decode"", + action = ""store_true"", + help = ""decode: DeepSMILES to SMILES"") + # parse CLI ---------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output = open(args.output_fn, 'w') + rings = args.rings + branches = args.branches + do_encode = args.do_encode + do_decode = args.do_decode + if do_decode: + do_encode = False + assert(not (do_encode and do_decode)) + if not (rings or branches): + print(""use at least --no-rings or --no-branches"", + file=sys.stderr) + sys.exit(1) + count = 0 + # work ---------------------------------------------- + smi_supplier = RobustSmilesSupplier(input_fn) + converter = deepsmiles.Converter(rings, branches) + if do_encode: + + for smi, name in smi_supplier: + deep_smi = encode(converter, smi) + print(""%s\t%s"" % (deep_smi, name), file=output) + count += 1 + else: # decode + for deep_smi, name in smi_supplier: + smi = decode(converter, deep_smi) + if smi != None: + print(""%s\t%s"" % (smi, name), file=output) + count += 1 + after = time.time() + dt = after - before + print(""%d molecules at %.2f mol/s"" % (count, count / dt), file=sys.stderr) + output.close() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_ph4_type_atoms.py",".py","7095","187","#!/usr/bin/env python3 + +# usage: list_features.py molecules.sdf + +import molenc_common +import os, sys, time +from rdkit import RDConfig +from rdkit import Chem +from rdkit.Chem import AllChem + +def open_fn(fn): + res = None + try: + res = open(fn, 'r') + except IOError: + print('ph4_type_atoms.py: open_fn: could not open file %s' % fn, + file = sys.stderr) + sys.exit(1) + return res + +# create the features factory +fn = os.path.join(RDConfig.RDDataDir, 'BaseFeatures.fdef') +fdef_str = open_fn(fn).read() +factory = AllChem.BuildFeatureFactoryFromString(fdef_str) +feature_defs = factory.GetFeatureDefs() + +## documentation +# feature_family_to_char = { 'Donor': 'D', +# 'Acceptor': 'A', +# 'PosIonizable': 'P', +# 'NegIonizable': 'N', +# 'Aromatic': 'a', +# 'Hydrophobe': 'H', +# 'LumpedHydrophobe': 'h', +# 'ZnBinder': 'Z' } + +# feature defs come from factory.GetFeaturesDef() +# I used all the keys found on 18/10/2018 DD/MM/YYYY +acceptor = feature_defs['Acceptor.SingleAtomAcceptor'] +arom4 = feature_defs['Aromatic.Arom4'] +arom5 = feature_defs['Aromatic.Arom5'] +arom6 = feature_defs['Aromatic.Arom6'] +arom7 = feature_defs['Aromatic.Arom7'] +arom8 = feature_defs['Aromatic.Arom8'] +donor = feature_defs['Donor.SingleAtomDonor'] +hydro1 = feature_defs['Hydrophobe.ChainTwoWayAttach'] +hydro2 = feature_defs['Hydrophobe.ThreeWayAttach'] +lhydro1 = feature_defs['LumpedHydrophobe.Nitro2'] +lhydro2 = feature_defs['LumpedHydrophobe.RH3_3'] +lhydro3 = feature_defs['LumpedHydrophobe.RH4_4'] +lhydro4 = feature_defs['LumpedHydrophobe.RH5_5'] +lhydro5 = feature_defs['LumpedHydrophobe.RH6_6'] +lhydro6 = feature_defs['LumpedHydrophobe.iPropyl'] +lhydro7 = feature_defs['LumpedHydrophobe.tButyl'] +neg = feature_defs['NegIonizable.AcidicGroup'] +pos1 = feature_defs['PosIonizable.BasicGroup'] +pos2 = feature_defs['PosIonizable.Guanidine'] +pos3 = feature_defs['PosIonizable.Imidazole'] +pos4 = feature_defs['PosIonizable.PosN'] +Zn1 = feature_defs['ZnBinder.ZnBinder1'] +Zn2 = feature_defs['ZnBinder.ZnBinder2'] +Zn3 = feature_defs['ZnBinder.ZnBinder3'] +Zn4 = feature_defs['ZnBinder.ZnBinder4'] +Zn5 = feature_defs['ZnBinder.ZnBinder5'] +Zn6 = feature_defs['ZnBinder.ZnBinder6'] + +acc_pat = Chem.MolFromSmarts(acceptor) +arom4_pat = Chem.MolFromSmarts(arom4) +arom5_pat = Chem.MolFromSmarts(arom5) +arom6_pat = Chem.MolFromSmarts(arom6) +arom7_pat = Chem.MolFromSmarts(arom7) +arom8_pat = Chem.MolFromSmarts(arom8) +donor_pat = Chem.MolFromSmarts(donor) +hydro1_pat = Chem.MolFromSmarts(hydro1) +hydro2_pat = Chem.MolFromSmarts(hydro2) +lhydro1_pat = Chem.MolFromSmarts(lhydro1) +lhydro2_pat = Chem.MolFromSmarts(lhydro2) +lhydro3_pat = Chem.MolFromSmarts(lhydro3) +lhydro4_pat = Chem.MolFromSmarts(lhydro4) +lhydro5_pat = Chem.MolFromSmarts(lhydro5) +lhydro6_pat = Chem.MolFromSmarts(lhydro6) +lhydro7_pat = Chem.MolFromSmarts(lhydro7) +neg_pat = Chem.MolFromSmarts(neg) +pos1_pat = Chem.MolFromSmarts(pos1) +pos2_pat = Chem.MolFromSmarts(pos2) +pos3_pat = Chem.MolFromSmarts(pos3) +pos4_pat = Chem.MolFromSmarts(pos4) +Zn1_pat = Chem.MolFromSmarts(Zn1) +Zn2_pat = Chem.MolFromSmarts(Zn2) +Zn3_pat = Chem.MolFromSmarts(Zn3) +Zn4_pat = Chem.MolFromSmarts(Zn4) +Zn5_pat = Chem.MolFromSmarts(Zn5) +Zn6_pat = Chem.MolFromSmarts(Zn6) + +def matching_indexes(mol, pat_str): + res = [] + pat = mol.GetSubstructMatches(pat_str) + for i in pat: + for j in i: + res.append(j) + return res + +def get_ph4_feats(mol): + acc_match = matching_indexes(mol, acc_pat) + arom4_match = matching_indexes(mol, arom4_pat) + arom5_match = matching_indexes(mol, arom5_pat) + arom6_match = matching_indexes(mol, arom6_pat) + arom7_match = matching_indexes(mol, arom7_pat) + arom8_match = matching_indexes(mol, arom8_pat) + donor_match = matching_indexes(mol, donor_pat) + hydro1_match = matching_indexes(mol, hydro1_pat) + hydro2_match = matching_indexes(mol, hydro2_pat) + lhydro1_match = matching_indexes(mol, lhydro1_pat) + lhydro2_match = matching_indexes(mol, lhydro2_pat) + lhydro3_match = matching_indexes(mol, lhydro3_pat) + lhydro4_match = matching_indexes(mol, lhydro4_pat) + lhydro5_match = matching_indexes(mol, lhydro5_pat) + lhydro6_match = matching_indexes(mol, lhydro6_pat) + lhydro7_match = matching_indexes(mol, lhydro7_pat) + neg_match = matching_indexes(mol, neg_pat) + pos1_match = matching_indexes(mol, pos1_pat) + pos2_match = matching_indexes(mol, pos2_pat) + pos3_match = matching_indexes(mol, pos3_pat) + pos4_match = matching_indexes(mol, pos4_pat) + zn1_match = matching_indexes(mol, Zn1_pat) + zn2_match = matching_indexes(mol, Zn2_pat) + zn3_match = matching_indexes(mol, Zn3_pat) + zn4_match = matching_indexes(mol, Zn4_pat) + zn5_match = matching_indexes(mol, Zn5_pat) + zn6_match = matching_indexes(mol, Zn6_pat) + atom_index_to_features = {} + # create all needed sets, empty for the moment + # we use a set of features so that there are no duplicated features for + # a given atom + for a in mol.GetAtoms(): + id = a.GetIdx() + atom_index_to_features[id] = set([]) + for i in acc_match: + atom_index_to_features[i].add('A') + for arom in [arom4_match, arom5_match, arom6_match, arom7_match, arom8_match]: + for i in arom: + atom_index_to_features[i].add('a') + for i in donor_match: + atom_index_to_features[i].add('D') + for hydro in [hydro1_match, hydro2_match]: + for i in hydro: + atom_index_to_features[i].add('H') + for lhydro in [lhydro1_match, lhydro2_match, lhydro3_match, lhydro4_match, lhydro5_match, lhydro6_match, lhydro7_match]: + for i in lhydro: + atom_index_to_features[i].add('h') + for i in neg_match: + atom_index_to_features[i].add('N') + for pos in [pos1_match, pos2_match, pos3_match, pos4_match]: + for i in pos: + atom_index_to_features[i].add('P') + for zn in [zn1_match, zn2_match, zn3_match, zn4_match, zn5_match, zn6_match]: + for i in zn: + atom_index_to_features[i].add('Z') + return atom_index_to_features + +def get_mol_feats(mol): + feats = get_ph4_feats(mol) + for a in mol.GetAtoms(): + id = a.GetIdx() + features = feats[id] + if len(features) == 0: + print(""%d _"" % id) # '_' means no ph4 feat. + else: + l = list(features) + l.sort() # canonicalize feats list for given atom + str = "" "".join(c for c in l) + print(""%d %s"" % (id, str)) + +if __name__ == '__main__': + before = time.time() + mol_supplier = Chem.SDMolSupplier(sys.argv[1]) + count = 0 + for mol in mol_supplier: + print(""#atoms:%d %s"" % (mol.GetNumAtoms(), mol.GetProp('_Name'))) + get_mol_feats(mol) + molenc_common.print_bonds(mol) + molenc_common.print_distance_matrix(mol) + count += 1 + after = time.time() + dt = after - before + print(""%d molecules at %.2f mol/s"" % (count, count / dt), file=sys.stderr) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_scan.py",".py","1946","59","#!/usr/bin/env python3 + +# wildcard atom scan of molecules +# for each molecule, output all variants where +# a single heavy atom at a time is switched to the SMILES wildcard atom '*' + +import rdkit, sys, time +from rdkit import Chem +# from rdkit.Chem import rdChemReactions + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + words = line.split() + smile = words[0] + name = "" "".join(words[1:]) # everything after the SMILES string + yield (name, smile) + +if __name__ == '__main__': + before = time.time() + argc = len(sys.argv) + if argc != 2: + print(""usage: %s input.smi"" % sys.argv[0]) + sys.exit(1) + input = sys.argv[1] + count = 0 + wildcard = Chem.Atom(0) + for name, orig_smile in RobustSmilesMolSupplier(input): + mol = Chem.MolFromSmiles(orig_smile) + # output original molecule first + print(""%s\t%s"" % (orig_smile, name)) + num_atoms = mol.GetNumAtoms() + # then output its variants + for i in range(num_atoms): + editable = Chem.EditableMol(mol) + editable.ReplaceAtom(i, wildcard, preserveProps=True) + edited = editable.GetMol() + smi = Chem.MolToSmiles(edited) + print(""%s\t%s_%d"" % (smi, name, i)) + count += 1 + after = time.time() + dt = after - before + print(""%d molecules at %.2f mol/s"" % (count, count / dt), file=sys.stderr) + +# # original code by @Iwatobipen +# # replace any aromatic carbon to aromatic nitrogen. +# # TODO: does not compile +# def nitrogen_scan(mol_in): +# out_mol_list = [] +# used = set() +# rxn = rdChemReactions.ReactionFromSmarts(""[c:1][H]>>[n:1]"") +# products = rxn.RunReactants([mol_in]) +# for p in products: +# smi = Chem.MolToSmiles(Chem.RemoveHs(p)) +# if smi not in used: +# used.add(smi) +# out_mol_list.append(p) +# return out_mol_list +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_qed.py",".py","2010","59","#!/usr/bin/env python3 +# +# Copyright (C) 2023, Francois Berenger +# Tsuda laboratory, The University of Tokyo, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# Compute QED for each input SMILES +# scores about 300 molecule/s on a single core +# +# requires: installing qed from sources (pip3 package broken as of 23/01/2023) +# cf. https://github.com/silicos-it/qed +# an open-source implementation of ""Quantifying the chemical beauty of drugs"" +# https://doi.org/10.1038/nchem.1243 + +import argparse, rdkit, sys +from qed import qed +from rdkit import Chem + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for i, line in enumerate(f): + words = line.split() + smile = words[0] + name = words[1] + yield (i, Chem.MolFromSmiles(smile), name) + +def main(): + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""Compute Quantitative Estimate of Drug-likeness (QED)"") + parser.add_argument(""-i"", metavar = ""input_smi"", dest = ""input_smi"", + help = ""input SMILES file"") + parser.add_argument(""-o"", metavar = ""output_tsv"", dest = ""output_tsv"", + help = ""output CSV file"") + # parse CLI + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_smi = args.input_smi + output_tsv = args.output_tsv + out_count = 0 + error_count = 0 + with open(output_tsv, 'w') as out_file: + for i, mol, name in RobustSmilesMolSupplier(input_smi): + if mol is None: + error_count += 1 + else: + score = qed.default(mol, False) + print(""%s\t%f"" % (name, score), file=out_file) + out_count += 1 + total_count = out_count + error_count + print(""read: %d errors: %d"" % (out_count, error_count), + file=sys.stderr) + +if __name__ == '__main__': + main() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_fscan.py",".py","2577","66","#!/usr/bin/env python3 +# +# Fluorine scan of a molecule +# create all analogs of input molecule where one heavy atom +# at a time has all of its hydrogens replaced by F +# optionally, do this only for heteroatoms + +import argparse, rdkit, sys +from rdkit import Chem + +def RobustSmilesMolSupplier(input_fn): + with open(input_fn) as f: + for line in f: + strip = line.strip() + toks = strip.split() + smi = toks[0] + toks.reverse() + name = toks[0] + yield (smi, name) + +fluor = Chem.Atom(9) + +if __name__ == '__main__': + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""compute atom types and distances"") + parser.add_argument(""-i"", metavar = ""input.smi"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.smi"", dest = ""output_fn"", + help = ""molecules output file"") + parser.add_argument('--hetero', dest='only_heteroatoms', action='store_true', + help = ""only scan heteroatoms"") + # parse CLI + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output_fn = args.output_fn + only_hetero = args.only_heteroatoms + with open(output_fn, 'w') as out: + for smi, name in RobustSmilesMolSupplier(input_fn): + # output original molecule first + print(""%s\t%s"" % (smi, name), file=out) + mol = Chem.MolFromSmiles(smi) + mol = Chem.AddHs(mol) + # then output its fluorinated analogs + count = 1 + for a in mol.GetAtoms(): + anum = a.GetAtomicNum() + if anum > 1 and ((not only_hetero) or anum != 6): + # heavy atom + if a.GetTotalNumHs(includeNeighbors=True) >= 1: + # hydrogens attached + editable = Chem.EditableMol(mol) + for neighb in a.GetNeighbors(): + if neighb.GetAtomicNum() == 1: + # Fluorine instead + a_j = neighb.GetIdx() + editable.ReplaceAtom(a_j, fluor) + edited = editable.GetMol() + smi = Chem.MolToSmiles(edited) + print(""%s\t%s_%d"" % (smi, name, count), file=out) + count += 1 +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_panascan.py",".py","3122","85","#!/usr/bin/env python3 + +# Copyright (C) 2021, Francois Berenger +# Yamanishi laboratory, +# Department of Bioscience and Bioinformatics, +# Faculty of Computer Science and Systems Engineering, +# Kyushu Institute of Technology, +# 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan. + +# Implementation of +# ""Positional Analogue Scanning: An Effective Strategy for +# Multiparameter Optimization in Drug Design"". +# Pennington, L. D., Aquila, B. M., Choi, Y., Valiulin, R. A., & Muegge, I. +# Journal of medicinal chemistry (2020). +# https://doi.org/10.1021/acs.jmedchem.9b02092 + +import argparse +import rdkit +import time +import random +from rdkit import Chem +from rdkit.Chem import AllChem +import sys + +from molenc_common import RobustSmilesMolSupplier + +def positional_analog_scan(mol, smarts_patt = '[cH]', + smi_substs = ['N','CF','CC','CO', + 'CCN','CCl','CC(F)(F)(F)','COC']): + res = [] + ss = set() # a string set + patt = Chem.MolFromSmarts(smarts_patt) + for smi in smi_substs: + subst = Chem.MolFromSmiles(smi) + analogs = AllChem.ReplaceSubstructs(mol, patt, subst) + for a in analogs: + analog_smi = Chem.MolToSmiles(a) # canonicalization + # remove duplicates + if analog_smi not in ss: + res.append(analog_smi) + ss.add(analog_smi) + return res + +if __name__ == '__main__': + before = time.time() + # CLI options + parser = argparse.ArgumentParser( + description = ""Positional Analog Scanning of each input molecule"") + parser.add_argument(""-i"", metavar = ""input.smi"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.smi"", dest = ""output_fn"", + help = ""analogs output file"") + parser.add_argument(""--rand-one"", dest = ""rand_one"", action = ""store_true"", + default = False, + help = ""output only one randomly-chosen analog \ + per input molecule"") + # parse CLI ---------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + rand_one = args.rand_one + output = open(args.output_fn, 'w') + count = 0 + # work ---------------------------------------------- + mol_supplier = RobustSmilesMolSupplier(input_fn) + for name, mol in mol_supplier: + analogs = positional_analog_scan(mol) + if rand_one: + l = list(analogs) + ana_smi = random.choice(l) + print(""%s\t%s_ANA%03d"" % (ana_smi, name, 0), + file=output) + else: # print them all + for i, ana_smi in enumerate(analogs): + print(""%s\t%s_ANA%03d"" % (ana_smi, name, i), + file=output) + count += 1 + after = time.time() + dt = after - before + print(""%d molecules at %.2f mol/s"" % (count, count / dt), file=sys.stderr) + output.close() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_thash.py",".py","773","26","#!/usr/bin/env python3 +# +# Copyright (C) 2024, Francois Berenger +# Tsuda laboratory, The University of Tokyo, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# append to stdout tautomer_hash to lines of a provided SMILES file + +import rdkit, sys, typing +from rdkit import Chem +from rdkit.Chem import RegistrationHash +from rdkit.Chem.RegistrationHash import HashLayer + +input_fn = sys.argv[1] + +def get_rdkit_tautomer_hash(smi: str) -> str: + mol = Chem.MolFromSmiles(smi) + layers = RegistrationHash.GetMolLayers(mol) + return layers[HashLayer.TAUTOMER_HASH] + +for line in open(input_fn).readlines(): + stripped = line.strip() + smi = stripped.split()[0] + taut_hash = get_rdkit_tautomer_hash(smi) + print('%s\t%s' % (stripped, taut_hash)) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_rdfrag.py",".py","6306","178","#!/usr/bin/env python3 +# +# Copyright (C) 2023, Francois Berenger +# BRICS or RECAP molecular fragmentation using rdkit (command-line tool) + +import argparse, rdkit, re, sys, sympy, time + +from molenc_common import RobustSmilesMolSupplier +from rdkit import Chem +from rdkit.Chem import BRICS, Draw, Recap + +# set of atom map nums +def atom_map_nums(mol): + s = set() + for a in mol.GetAtoms(): + curr_id = a.GetAtomMapNum() + if curr_id != 0: + s.add(curr_id) + return s + +# remap elements of an arbitrary integer set w/ cardinality N from 1 to N +def renumber_atom_map_nums(mol): + s = atom_map_nums(mol) + # compute the mapping + ht = {} + for i, x in enumerate(s): + ht[x] = i + 1 # AtomMapNums start at 1 + # apply it + for a in mol.GetAtoms(): + curr_id = a.GetAtomMapNum() + if curr_id != 0: + a.SetAtomMapNum(ht[curr_id]) + +# dump molecule in 2D to a .png file +def png_dump_mol(fn, mol): + mol_to_draw = Chem.Mol(mol) # copy mol + renumber_atom_map_nums(mol_to_draw) + for a in mol_to_draw.GetAtoms(): + curr_id = a.GetAtomMapNum() + if curr_id != 0: + # clear AtomMapNum: they look uggly in molecular drawings + a.SetAtomMapNum(0) + # use atomNote instead + a.SetProp(""atomNote"", str(curr_id)) + print('creating %s' % fn, file=sys.stderr) + Draw.MolToFile(mol_to_draw, fn, size=(1500,1500)) + +digits_star = re.compile('[0-9]+\*') + +# ignore BRICS ""bond tags"" for the moment +def remove_BRICS_tags(smi): + return re.sub(digits_star, '*', smi) + +def fragment(recap, mol): + if recap: + hierarch = Recap.RecapDecompose(mol) + return hierarch.GetLeaves().keys() + else: + frags = BRICS.BRICSDecompose(mol) + res = [] + for f in frags: + res.append(remove_BRICS_tags(f)) + return res + +# robust a.GetProp(str_key) +def get_atom_prop(a, key): + try: + return a.GetProp(key) + except KeyError: + return """" + +def dict_value_or_none(d, k): + try: + return d[k] + except KeyError: + return None + +def frag_ids_to_atom_map_nums(mol): + s = atom_map_nums(mol) + count = 1 + ht = {} + # only one of the two fragmenting schemes has already assigned AtomMapNums + # the other scheme assigns atom properties under the key ""frag_ids"" + if len(s) == 0: + # map atom props to atom map nums + for a in mol.GetAtoms(): + curr_id = get_atom_prop(a, ""frag_ids"") + if curr_id != """": + val = dict_value_or_none(ht, curr_id) + if val == None: + # new id for this set of fragments + ht[curr_id] = count + a.SetAtomMapNum(count) + count += 1 + else: + # already seen set of fragments + a.SetAtomMapNum(val) + +def fragment_RECAP_or_BRICS(recap, out, mol, name): + frags = fragment(recap, mol) + num_frags = len(frags) + scheme = """" + if recap: + scheme = ""RECAP"" + else: + scheme = ""BRICS"" + print(""%d %s fragments in %s"" % (num_frags, scheme, name)) + if num_frags <= 1: + print(""could not fragment: %s"" % Chem.MolToSmiles(mol), + file=sys.stderr) + else: + frag_idx = 0 + for smi in frags: + # /!\ interpreting a SMILES as a SMARTS: is that _really_ safe? /!\ + patt = Chem.MolFromSmarts(smi) + patt_atoms = patt.GetAtoms() + matches = mol.GetSubstructMatches(patt) + if len(matches) == 0: + print(""fragment not found: %s"" % smi, file=sys.stderr) + for match in matches: + for i, a_idx in enumerate(match): + patt_a = patt_atoms[i] + # the dummy atom is not part of the fragment + if patt_a.GetAtomicNum() > 0: + a = mol.GetAtomWithIdx(a_idx) + curr_id = get_atom_prop(a, ""frag_ids"") + # don't overwrite already annotated fragments + if curr_id == """": + a.SetProp(""frag_ids"", str(frag_idx)) + else: + # atom is part of several fragments + # (RECAP is a hierarchical fragmentation scheme) + new_id = ""%s,%s"" % (curr_id, str(frag_idx)) + a.SetProp(""frag_ids"", new_id) + # a fragment can be matched several times + # but we want each final molecular fragment to have a different id + frag_idx += 1 + png_fn = '%s.png' % name + frag_ids_to_atom_map_nums(mol) + png_dump_mol(png_fn, mol) + res = Chem.MolToSmiles(mol) + print('%s\t%s_%s_fragments' % (res, name, scheme), file=out) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""fragment molecules using BRICS or RECAP"") + parser.add_argument(""-i"", metavar = ""input.smi"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.smi"", dest = ""output_fn"", + help = ""output file"") + parser.add_argument(""--recap"", dest = ""recap"", action ='store_true', + default = True, help = ""use RECAP (default)"") + parser.add_argument(""--brics"", dest = ""recap"", action ='store_false', + help = ""use BRICS"") + # parse CLI + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output_fn = args.output_fn + recap = args.recap + count = 0 + # fragmentation --------------------------------------------------------- + with open(output_fn, 'w') as output: + mol_supplier = RobustSmilesMolSupplier(input_fn) + for name, mol in mol_supplier: + print(""#atoms:%d %s"" % (mol.GetNumAtoms(), name)) + fragment_RECAP_or_BRICS(recap, output, mol, name) + count += 1 + after = time.time() + dt = after - before + print(""fragmented %d molecule(s) at %.2f Hz"" % (count, count / dt), + file=sys.stderr) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_lizard.py",".py","7635","193","#!/usr/bin/env python3 + +# Copyright (C) 2020, Francois Berenger +# Yamanishi laboratory, +# Department of Bioscience and Bioinformatics, +# Faculty of Computer Science and Systems Engineering, +# Kyushu Institute of Technology, +# 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan. +# +# Simple molecular encoder using a handful of molecular descriptors. +# type signature: molecule -> (MolW,cLogP,TPSA,RotB,HBA,HBD,FC) +# Why is this script called molenc_lizard.py +# First, because it is part of the molenc project. +# Second, because if you have a little bit of imagination, a lizard +# is just a very small dragon. +# +# The --remove-aliens option was inspired by +# Tran-Nguyen, V. K., Jacquemard, C., & Rognan, D. (2020). +# ""LIT-PCBA: An Unbiased Data Set for Machine Learning and Virtual Screening."" +# Journal of Chemical Information and Modeling. +# https://doi.org/10.1021/acs.jcim.0c00155 + +import argparse, rdkit, sys +from rdkit import Chem +from rdkit.Chem import AllChem, Descriptors, Lipinski +from rdkit.Chem.AtomPairs import Pairs + +PeriodicTable = Chem.GetPeriodicTable() + +def RobustSmilesMolSupplier(filename): + with open(filename) as input: + for i, line in enumerate(input.readlines()): + words = line.strip().split() + smile = """" + name = ""NO_NAME"" + try: + smile = words[0] + name = words[1] + yield (i, Chem.MolFromSmiles(smile), name) + except IndexError: + # not enough fields on line + yield (i, None, name) + +# detect strange molecules +def is_alien(MolW, cLogP, TPSA, RotB, HBA, HBD, FC): + # Step 1: TODO? + # Organic compound filter. Molecules bearing at + # least one atom other than H, C, N, O, P, S, F, Cl, Br, and I + # were removed. + # Step 2: ignored; too complex (using IC50 curve shape + other things). + # Step 3: Molecular property range filter. Remaining + # actives and inactives were kept if: + # rdkit's MolW unit seems to be g/mol + # 1C -> 12Da = 12g/mol <=> 1Da = 1g/mol + return (MolW <= 150 or MolW >= 800 or # 150 < MolW < 800 Da + cLogP <= -3.0 or cLogP >= 5.0 or # −3.0 < AlogP < 5.0 + RotB >= 15 or # RotB < 15 + HBA >= 10 or # HBA < 10 + HBD >= 10 or # HBD < 10 + FC <= -2 or FC >= 2) # −2.0 < FC < 2.0 + +# message string describing the alien +def alien_diagnose(i, name, MolW, cLogP, TPSA, RotB, HBA, HBD, FC): + err_msg = ""%d %s"" % (i, name) + if MolW <= 150: + err_msg += ""; (MolW=%g) <= 150"" % MolW + if MolW >= 800: + err_msg += ""; (MolW=%g) >= 800"" % MolW + if cLogP <= -3.0: + err_msg += ""; (cLogP=%g) <= -3"" % cLogP + if cLogP >= 5.0: + err_msg += ""; (cLogP=%g) >= 5"" % cLogP + if RotB >= 15: + err_msg += ""; (RotB=%d) >= 15"" % RotB + if HBA >= 10: + err_msg += ""; (HBA=%d) >= 10"" % HBA + if HBD >= 10: + err_msg += ""; (HBD=%d) >= 10"" % HBD + if FC <= -2: + err_msg += ""; (FC=%d) <= -2"" % FC + if FC >= 2: + err_msg += ""; (FC=%d) >= 2"" % FC + return err_msg + +def fun_for_mol_desc(mol_desc): + if mol_desc == ""MolW"": + return Descriptors.MolWt + elif mol_desc == ""HA"": + return Lipinski.HeavyAtomCount + elif mol_desc == ""cLogP"": + return Descriptors.MolLogP + elif mol_desc == ""AR"": + return Lipinski.NumAromaticRings + elif mol_desc == ""TPSA"": + return Descriptors.TPSA + elif mol_desc == ""RotB"": + return Descriptors.NumRotatableBonds + elif mol_desc == ""HBA"": + return Descriptors.NumHAcceptors + elif mol_desc == ""HBD"": + return Descriptors.NumHDonors + elif mol_desc == ""FC"": + return Chem.rdmolops.GetFormalCharge + else: + print(""FATAL: molenc_lizard.py: fun_for_mol_desc: \ + unsupported: %s"" % mol_desc, file=sys.stderr) + exit(1) + +def main(): + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""Project molecules read from a SMILES file into an 10D \ + space whose dimensions are molecular descriptors: \ + (MolW, HA, cLogP, AR, TPSA, RotB, HBA, HBD, FC)"") + parser.add_argument(""-i"", metavar = ""input_smi"", dest = ""input_smi"", + help = ""input SMILES file"") + parser.add_argument(""-o"", metavar = ""output_csv"", dest = ""output_csv"", + help = ""output CSV file"") + parser.add_argument('--no-header', dest='no_header', + action='store_true', default=False, + help = ""no CSV header in output file"") + parser.add_argument('--only', metavar = ""mol_desc"", dest='mol_desc', + default=""all"", + help = ""if you want to compute just one molecular \ + descriptor"") + # just warn about aliens by default + parser.add_argument('--remove-aliens', dest='rm_aliens', + action='store_true', default=False, + help = ""don't allow aliens in output file"") + # parse CLI + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_smi = args.input_smi + output_csv = args.output_csv + rm_aliens = args.rm_aliens + no_header = args.no_header + mol_desc = args.mol_desc + out_count = 0 + alien_count = 0 + error_count = 0 + fun = None + if mol_desc != ""all"": + fun = fun_for_mol_desc(mol_desc) + with open(output_csv, 'w') as out_file: + if not no_header: + if mol_desc == ""all"": + print(""#name,MolW,HA,cLogP,AR,TPSA,RotB,HBA,HBD,FC"", + file=out_file) + else: + print(""#name,%s"" % mol_desc, file=out_file) + for i, mol, name in RobustSmilesMolSupplier(input_smi): + if mol is None: + error_count += 1 + else: + if mol_desc == ""all"": + MolW = Descriptors.MolWt(mol) + HA = Lipinski.HeavyAtomCount(mol) + cLogP = Descriptors.MolLogP(mol) + AR = Lipinski.NumAromaticRings(mol) + TPSA = Descriptors.TPSA(mol) + RotB = Descriptors.NumRotatableBonds(mol) + HBA = Descriptors.NumHAcceptors(mol) + HBD = Descriptors.NumHDonors(mol) + FC = Chem.rdmolops.GetFormalCharge(mol) + alien = is_alien(MolW, cLogP, TPSA, RotB, HBA, HBD, FC) + if alien: + alien_str = alien_diagnose(i, name, MolW, cLogP, TPSA, + RotB, HBA, HBD, FC) + print(""WARN: %s"" % alien_str, file=sys.stderr) + alien_count += 1 + if (not alien) or (not rm_aliens): + csv_line = ""%s,%g,%d,%g,%d,%g,%d,%d,%d,%d"" % \ + (name, MolW, HA, cLogP, AR, TPSA, RotB, + HBA, HBD, FC) + print(csv_line, file=out_file) + out_count += 1 + else: + csv_line = ""%s,%g"" % (name, fun(mol)) + print(csv_line, file=out_file) + out_count += 1 + total_count = out_count + error_count + if rm_aliens: + total_count += alien_count + print(""encoded: %d aliens: %d errors: %d total: %d"" % \ + (out_count, alien_count, error_count, total_count), + file=sys.stderr) + +if __name__ == '__main__': + main() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_ligprep.sh",".sh","3642","122","#!/usr/bin/env bash + +set -u +#set -x # DEBUG + +# from SMILES to 3D protonated molecules with partial charges ready-to-dock + +# check input filename was given +if [ $# -eq 0 ]; then + echo ""usage:"" + echo ""molenc_ligprep.sh molecules.smi"" + echo "" [--fast]: protonate:obabel; 3D:omega; molcharge:MMFF94"" + echo "" [--HA]: protonate:tautomers; 3D:omega; molcharge:AM1BCC"" + echo "" [--free]: protonate:obabel; 3D:obabel; obabel:MMFF94"" + exit 1 +fi + +FAST_MODE="""" +HIGH_ACCURACY="""" +FREE_MODE=""TRUE"" # default + +IN=$1 +BASEDIR=`dirname $IN` +BASENAME=`basename $IN .smi` +OUT=${BASEDIR}'/'${BASENAME} + +RHEL_OE_BASE=~/usr/openeye/arch/redhat-RHEL7-x64 +UBUN_OE_BASE=~/usr/openeye/arch/Ubuntu-18.04-x64 + +# parse CLI options +while [[ $# -gt 0 ]]; do + key=""$1"" + case $key in + --fast) + FAST_MODE=""TRUE"" + HIGH_ACCURACY="""" + FREE_MODE="""" + echo ""selected fast mode"" + shift # past argument + ;; + --HA) + HIGH_ACCURACY=""TRUE"" + FAST_MODE="""" + FREE_MODE="""" + echo ""selected HA mode"" + shift # past argument + ;; + --free) + FREE_MODE=""TRUE"" + FAST_MODE="""" + HIGH_ACCURACY="""" + echo ""selected free mode"" + shift # past argument + ;; + *) # unknown option or input file + echo ""input file: ""$1 + shift # past argument + ;; + esac +done + +PROTONATED=${OUT}_taut74.smi +CONFORMER=${OUT}_taut74_1conf.sdf +CHARGED=${OUT}_taut74_1conf_mmff.mol2 + +# fast mode ------------------------------------------------------------------- + +if [ ""$FAST_MODE"" == ""TRUE"" ]; then + echo ""running fast mode"" + # protonation state at physiological pH + obabel $IN -O $PROTONATED -p 7.4 + # lowest energy conformer w/ OE omega + ${RHEL_OE_BASE}/omega/omega2 \ + -strictstereo false -maxconfs 1 -in $PROTONATED -out $CONFORMER + # assign partial charges + ${RHEL_OE_BASE}/quacpac/molcharge \ + -method mmff -in $CONFORMER -out $CHARGED +fi + +# high accuracy mode ---------------------------------------------------------- + +if [ ""$HIGH_ACCURACY"" == ""TRUE"" ]; then + echo ""running HA mode"" + PROTONATED=${OUT}_OEtaut74.smi + CONFORMER=${OUT}_OEtaut74_1conf.sdf + CHARGED=${OUT}_OEtaut74_1conf_am1bcc.mol2 + # most reasonable tautomer at physiological pH (7.4) + ~/usr/openeye/bin/tautomers -pkanorm true -rank true -maxtoreturn 1 \ + -maxtime 10 -in $IN -out $PROTONATED + # lowest energy conformer w/ OE omega + ${RHEL_OE_BASE}/omega/omega2 \ + -maxtime 10 -strictstereo false -maxconfs 1 \ + -in $PROTONATED -out $CONFORMER + # assign partial charges; no -maxtime CLI option hence timeout + timeout 10s ${RHEL_OE_BASE}/quacpac/molcharge \ + -method am1bcc -in $CONFORMER -out $CHARGED +fi + +# free / open-source mode ----------------------------------------------------- + +if [ ""$FREE_MODE"" == ""TRUE"" ]; then + echo ""running free mode"" + PROTONATED=${OUT}_taut74.smi + CONFORMER=${OUT}_taut74_1conf.sdf + CHARGED=${OUT}_taut74_1conf_mmff.mol2 + # protonation state at physiological pH and unsalt + obabel $IN -O $PROTONATED -p 7.4 -r + # lowest energy conformer + obabel $PROTONATED -O $CONFORMER --gen3D + # assign partial charges + obabel $CONFORMER -O $CHARGED --partialcharge mmff94 +fi + +# cleanup --------------------------------------------------------------------- + +# rm temp. files +rm -f $PROTONATED $CONFORMER + +# user feedback +wc -l $IN +grep -c '@MOLECULE' $CHARGED +","Shell" +"QSAR","UnixJunkie/molenc","bin/molenc_stable.py",".py","3431","85","#!/usr/bin/env python3 +# +# Copyright (C) 2024, Francois Berenger +# Tsuda laboratory, The University of Tokyo, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# stable filter: only non-reactive molecules are printed on stdout +# input line format: \t +# output line format: same as input + +import sys + +from rdkit import Chem +from rdkit.Chem import Descriptors + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + splits = line.strip().split(""\t"") # enforce TAB-separated + smile = splits[0] + try: + mol = Chem.MolFromSmiles(smile) + yield (mol, line) + except Exception: + print(""ERROR: cannot parse: %s"" % line, + file=sys.stderr) + +# Lisurek, M., Rupp, B., Wichard, J., Neuenschwander, M., von Kries, J. P., +# Frank, R., ... & Kühne, R. (2010). +# Design of chemical libraries with potentially bioactive molecules applying +# a maximum common substructure concept. Molecular diversity, 14(2), 401-408. +# SMARTS patterns kindly provided by Michael Lisurek +pat1 = Chem.MolFromSmarts('[C,c]S(=O)(=O)[F,Cl,Br,I]') # sulfonylhalide +pat2 = Chem.MolFromSmarts('[C,c]S(=O)(=O)O[CX4]') # sulfone_ester +pat3 = Chem.MolFromSmarts('C(=O)[F,Cl,Br,I]') # acylhalide +pat4 = Chem.MolFromSmarts('O=COC=O') # acidanhydride +pat5 = Chem.MolFromSmarts('c1([F,Cl,Br,I])ncccn1') # 2-halo_pyrimidine +pat6 = Chem.MolFromSmarts('[H]C=O') # aldehyde +pat7 = Chem.MolFromSmarts('C(=O)C(=O)') # 1,2-dicarbonyl +pat8 = Chem.MolFromSmarts('C1OC1') # epoxide +pat9 = Chem.MolFromSmarts('C1NC1') # aziridine +pat10 = Chem.MolFromSmarts('C(=O)S') # thioester +pat11 = Chem.MolFromSmarts('[#7]!@[#7]') # hydrazine +pat12 = Chem.MolFromSmarts('C=[CH2]') # ethenes +pat13 = Chem.MolFromSmarts('[H,*,!N][N;!R]=[C;!R]([*,H])[*,H]') # imine +pat14 = Chem.MolFromSmarts('[CX4]I') # alkyl_iodide +pat15 = Chem.MolFromSmarts('[Se]') # selenide +pat16 = Chem.MolFromSmarts('O-O') # peroxide +pat17 = Chem.MolFromSmarts('[NX3]!@[OX2]') # hetero-hetero_single_bond +pat18 = Chem.MolFromSmarts('[NX3]!@[NX3]') # hetero-hetero_single_bond +pat19 = Chem.MolFromSmarts('[NX3]!@[SX2]') # hetero-hetero_single_bond +pat20 = Chem.MolFromSmarts('[SX2]!@[SX2]') # hetero-hetero_single_bond +pat21 = Chem.MolFromSmarts('[SX2]!@[OX2]') # hetero-hetero_single_bond + +def stable_filter(mol): + return (not ( + mol.HasSubstructMatch(pat1) or + mol.HasSubstructMatch(pat2) or + mol.HasSubstructMatch(pat3) or + mol.HasSubstructMatch(pat4) or + mol.HasSubstructMatch(pat5) or + mol.HasSubstructMatch(pat6) or + mol.HasSubstructMatch(pat7) or + mol.HasSubstructMatch(pat8) or + mol.HasSubstructMatch(pat9) or + mol.HasSubstructMatch(pat10) or + mol.HasSubstructMatch(pat11) or + mol.HasSubstructMatch(pat12) or + mol.HasSubstructMatch(pat13) or + mol.HasSubstructMatch(pat14) or + mol.HasSubstructMatch(pat15) or + mol.HasSubstructMatch(pat16) or + mol.HasSubstructMatch(pat17) or + mol.HasSubstructMatch(pat18) or + mol.HasSubstructMatch(pat19) or + mol.HasSubstructMatch(pat20) or + mol.HasSubstructMatch(pat21))) + +input_fn = sys.argv[1] + +for mol, line in RobustSmilesMolSupplier(input_fn): + if stable_filter(mol): + # exact input lines replicated to the output + print(line, end='') +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_rbonds_filter.py",".py","2677","79","#!/usr/bin/env python3 +# +# Copyright (C) 2023, Francois Berenger +# Tsuda laboratory, Tokyo University, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# Only keep molecules with an acceptable number of rotatable bonds + +import argparse, re, sys, time +from rdkit import Chem +from rdkit.Chem import Descriptors + +regex = re.compile('\s') + +def find_whitespace(s): + m = re.search(regex, s) + if m == None: + return -1 + else: + return m.start() + +def parse_smiles_line(line): + fst_white = find_whitespace(line) + smi = '' + name = '' + if fst_white == -1: + # no whitespace separator: assume molecule has no name + # use the SMILES itself as the name, so this unnamed + # molecule will percolate instead of behing lost + smi = line + name = line + else: + smi = line[0:fst_white] + name = line[fst_white + 1:] + return Chem.MolFromSmiles(smi) + +def rbonds_filter(max_rbonds, mol): + if Descriptors.NumRotatableBonds(mol) <= max_rbonds: + return True + else: + return False + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser(description = ""filter out molecules w/ disallowed atoms"") + parser.add_argument(""-i"", metavar = ""input.smi"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.smi"", dest = ""output_fn"", + help = ""molecules output file"") + parser.add_argument('-r', metavar = ""MAX_ROT_BONDS_INT"", dest='max_rbonds', + default=-1, type=int, + help = ""maximum number of rotatable bonds allowed (default=NO_LIMIT"") + # parse CLI --------------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output_fn = args.output_fn + max_rbonds = args.max_rbonds + # parse CLI end ----------------------------------------------------------- + count = 0 + errors = 0 + with open(output_fn, 'w') as out: + with open(input_fn, 'r') as input: + for line in input.readlines(): + mol = parse_smiles_line(line.strip()) + if rbonds_filter(max_rbonds, mol): + out.write(""%s"" % line) + else: + errors += 1 + count += 1 + after = time.time() + dt = after - before + print(""%d molecules @ %.2fHz; removed %d"" % (count, count / dt, errors), + file=sys.stderr) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_histo.py",".py","4171","111","#!/usr/bin/env python3 +# +# compute histogram for data file (one value per line) + +import argparse, sys + +if __name__ == '__main__': + default_steps = 50 + # ----------------------------------------------------------- + parser = argparse.ArgumentParser( + description = ""Output histogram values for input file"") + parser.add_argument(""-i"", metavar = ""input.csv"", dest = ""input_fn"", + help = ""input file; one value per line"") + parser.add_argument(""-o"", metavar = ""output.csv"", dest = ""output_fn"", + help = ""output file for gnuplot histeps"") + parser.add_argument(""-n"", metavar = ""num_steps"", dest = ""num_steps"", + help = ""number of histogram steps (default=%d)"" % + default_steps, default = default_steps, type=int) + parser.add_argument(""-min"", metavar = ""min_val"", dest = ""min_val"", + help = ""minimum value (default=auto)"", + default=sys.float_info.max, type=float) + parser.add_argument(""-max"", metavar = ""max_val"", dest = ""max_val"", + help = ""maximum value (default=auto)"", + default=-sys.float_info.max, type=float) + parser.add_argument('--drop', dest='drop_values', + action='store_true', default=False, + help = ""drop values outside bounds"") + parser.add_argument('--norm', dest='normalize', + action='store_true', default=False, + help = ""normalize histogram"") + # parse CLI + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + + if len(sys.argv) == 1: + print(""usage: molenc_histo.py -i INPUT.csv -o OUTPUT.csv"", + file=sys.stderr) + exit(1) + + input_fn = args.input_fn + output_fn = args.output_fn + num_steps = float(args.num_steps) + mini = args.min_val + maxi = args.max_val + drop_values = args.drop_values + normalize = args.normalize + # ---------------------------------------------------------- + + with open(output_fn, 'w') as output: + # read in values + floats = [] + for line in open(input_fn).readlines(): + strip = line.strip() + x = float(strip) + if not drop_values: + floats.append(x) + elif (x >= mini and x <= maxi): + floats.append(x) + total = len(floats) + assert(total > 0) + + min_val = min(floats) + max_val = max(floats) + # if user provided bounds; we don't allow going over them + if drop_values and min_val < mini: + print(""FATAL: actual min < min_val: %f < %f"" % (min_val, mini), file=sys.stderr) + exit(1) + if drop_values and max_val > maxi: + print(""FATAL: actual max > max_val: %f > %f"" % (max_val, maxi), file=sys.stderr) + exit(1) + # for consistent histograms, the user will specify bounds + min_val = min(mini, min_val) + max_val = max(maxi, max_val) + + assert(min_val < max_val) + delta = (max_val - min_val) / num_steps + # print('DEBUG: min:%g max:%g steps:%d delta:%g' % + # (min_val, max_val, num_steps, delta), file=output) + + # initialize histogram + histo = {} + x = min_val + i = 0 + while x <= max_val + delta: + histo[i] = 0 + x += delta + i += 1 + + # finalize histogram + for x in floats: + assert(x >= min_val) + assert(x <= max_val) + hist_bin = int((x - min_val) / delta) + histo[hist_bin] += 1 + + # print histogram + x = min_val + i = 0 + while x <= max_val + delta: + x_val = min_val + float(i) * delta + y_val = histo[i] + if normalize: + print('%f %f' % (x_val, float(y_val)/float(total)), file=output) + else: + print('%f %d' % (x_val, y_val), file=output) + x += delta + i += 1 +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_get_tag.py",".py","2800","78","#!/usr/bin/env python3 +# +# Extract given tags from an SDF file; not parsing molecules for speed + +import argparse, gzip, re, sys + +class End_of_file(Exception): + pass + +def open_maybe_compressed_file(fn): + if fn.endswith("".gz""): + return gzip.open(fn, 'rt') + else: + return open(fn, 'rt') + +# regexp to capture an SDF tag (key) +# next line must contain the corresponding value +sdf_tag_name = re.compile('> <(.+)>') + +if __name__ == '__main__': + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""Extract listed properties from SDF file"") + parser.add_argument(""-i"", metavar = ""input.sdf[.gz]"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.txt"", dest = ""output_fn"", + help = ""output file"") + parser.add_argument('-t', metavar = 'tag1,tag2,...', dest = ""tags"", + help = ""comma-separated list of tags to extract"") + # parse CLI + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output_fn = args.output_fn + tags = args.tags.strip().split(',') + tags_set = set(tags) + # ------------------------------------------------------------------------- + res: dict[str,list[str]] = {} + for tag in tags: + res[tag] = [] + # capture all tags we are interested in + with open_maybe_compressed_file(input_fn) as input: + try: + while True: + line = input.readline() + if line == '': + raise End_of_file + elif line[0] == '>': + match = sdf_tag_name.match(line) + if match: + key = match.group(1) + if key in tags_set: + value: str = input.readline().strip() + prev_vals = res[key] + prev_vals.append(value) + res[key] = prev_vals + except End_of_file: + pass + # check all tags of interest were seen the same number of times + expected = len(res[tags[0]]) + for tag in tags: + if expected != len(res[tag]): + print('FATAL: expected: %d <> len(res[%s]) = %d' % \ + (expected, tag, len(res[tag])), file=sys.stderr) + exit(1) + # CSV output + values = [] + for tag in tags: + values.append(res[tag]) + with open(output_fn, 'w') as csv_out: + for i in range(expected): + for j in range(len(values)): + print(""%s"" % values[j][i], file=csv_out, end=',') + print("""", file=csv_out) # EOL +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_type_atoms.py",".py","3604","104","#!/usr/bin/env python3 + +# type atoms of a molecule a la atom pairs +# (nb. pi electrons if > 0, elt. symbol, nbHA neighbors) +# formal charges are ignored, as was the case in the seminal implementation +# of atom pairs, not sure this is very smart though + +import argparse, molenc_common, os, rdkit, sys, time +from enum import Enum +from rdkit import Chem +from rdkit import RDConfig +from rdkit.Chem import AllChem, Descriptors +from rdkit.Chem.AtomPairs import Pairs + +def RobustSmilesMolSupplier(filename): + with open(filename) as f: + for line in f: + words = line.split() + smile = words[0] + name = "" "".join(words[1:]) # everything after the SMILES string + yield (name, Chem.MolFromSmiles(smile)) + +def SdfMolSupplier(fn): + for mol in Chem.SDMolSupplier(fn): + if mol: + name = mol.GetProp('_Name') + yield (name, mol) + +def nb_heavy_atom_neighbors(a): + res = 0 + for neighb in a.GetNeighbors(): + if neighb.GetAtomicNum() != 1: + res += 1 + return res + +PeriodicTable = Chem.GetPeriodicTable() + +def string_of_charge(charge): + if charge == 0: return """" + elif charge == -1: return ""-"" + elif charge == 1: return ""+"" + else: return (""%+d"" % charge) + +def type_atom(a): + res = None + nb_pi_electrons = Pairs.Utils.NumPiElectrons(a) + symbol = PeriodicTable.GetElementSymbol(a.GetAtomicNum()) + nbHA = nb_heavy_atom_neighbors(a) + formal_charge = string_of_charge(a.GetFormalCharge()) + if nb_pi_electrons > 0: + res = ""%d%s%d%s"" % (nb_pi_electrons, symbol, nbHA, formal_charge) + else: + res = ""%s%d%s"" % (symbol, nbHA, formal_charge) + return res + +def encode_molecule(m): + return map(type_atom, m.GetAtoms()) + +def print_encoded_atoms(out, atoms): + for i, a in enumerate(atoms): + print(""%d %s"" % (i, a), file=out) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser( + description = ""compute atom types and distances"") + parser.add_argument(""-i"", metavar = ""input.{smi|sdf}"", dest = ""input_fn"", + help = ""molecules input file"") + parser.add_argument(""-o"", metavar = ""output.txt"", dest = ""output_fn"", + help = ""output file"") + parser.add_argument('--3D', dest='three_dimensions', action='store_true', + help = ""consider molecules in 3D (requires SDF)"") + parser.set_defaults(three_dimensions=False) + # parse CLI + if len(sys.argv) == 1: + # show help in case user has no clue of what to do + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output = open(args.output_fn, 'w') + mol_supplier = None + three_dimensions = args.three_dimensions + if three_dimensions or input_fn.endswith("".sdf""): + mol_supplier = SdfMolSupplier + elif input_fn.endswith("".smi""): + mol_supplier = RobustSmilesMolSupplier + else: + print(""molenc_type_atoms.py: input file not .smi or .sdf and no --3D"", + file=sys.stderr) + sys.exit(1) + count = 0 + for name, mol in mol_supplier(input_fn): + print(""#atoms:%d %s"" % (mol.GetNumAtoms(), name), file=output) + print_encoded_atoms(output, encode_molecule(mol)) + molenc_common.print_bonds(output, mol) + molenc_common.print_distance_matrix(output, mol, three_dimensions) + count += 1 + after = time.time() + dt = after - before + print(""%d molecules at %.2f mol/s"" % (count, count / dt), file=sys.stderr) + output.close() +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_nearest.py",".py","3715","105","#!/usr/bin/env python3 + +# Copyright (C) 2024, Francois Berenger +# Tsuda laboratory, Graduate School of Frontier Sciences, +# The University of Tokyo, Japan. +# +# Annotate a SMILES file using the nearest molecule found in another SMILES +# file according to the Tanimoto score for the given molecular fingerprint +# WARNING: this is O(N^2), so inefficient in case there are many +# ""reference"" molecules + +import argparse, rdkit, sys, time, typing + +from rdkit import Chem, DataStructs +from rdkit.Chem import rdFingerprintGenerator + +def hour_min_sec(): + tm = time.localtime() + return (tm.tm_hour, tm.tm_min, tm.tm_sec) + +# use this instead of print to log on stderr +def log(*args, **kwargs): + hms = hour_min_sec() + print('%02d:%02d:%02d ' % hms, file=sys.stderr, end='') + return print(*args, **kwargs, file=sys.stderr) + +def parse_smiles_line(line: str) -> tuple[str, str]: + # print(""DEBUG: %s"" % line) + split = line.strip().split() + smi = split[0] + name = split[1] + return (smi, name) + +generator = rdFingerprintGenerator.GetMorganGenerator(2, fpSize=2048) + +def ecfp4_of_mol(mol): + return generator.GetFingerprint(mol) + +def find_nearest(query_mol, ref_fps): + best_i = -1 + best_tani = 0.0 + query_fp = ecfp4_of_mol(query_mol) + for i, ref_fp in enumerate(ref_fps): + curr_tani = DataStructs.TanimotoSimilarity(query_fp, ref_fp) + if curr_tani > best_tani: + best_i = i + best_tani = curr_tani + return (best_i, best_tani) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser(description = 'find nearest molecule \ + (in fingerprint space)') + parser.add_argument('-i', + metavar = '', type = str, + dest = 'input_fn', + help = 'molecules to annotate (SMILES file)') + parser.add_argument('-r', + metavar = '', type = str, + dest = 'ref_fn', + default = '', + help = 'reference molecules (SMILES file)') + # parser.add_argument('-np', + # metavar = '', type = int, + # dest = 'nprocs', + # default = 1, + # help = 'max number of processes') + # parse CLI --------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + ref_fn = args.ref_fn + log(""computing FPs for ref. molecules..."") + ref_names = [] + ref_smi = [] + ref_fps = [] + with open(ref_fn, 'r') as input: + for line in input.readlines(): + strip = line.strip() + smi, name = parse_smiles_line(strip) + mol = Chem.MolFromSmiles(smi) + if mol != None: + ref_names.append(name) + ref_smi.append(smi) + ref_fps.append(ecfp4_of_mol(mol)) + log(""iterating over cand. molecules..."") + with open(input_fn, 'r') as input: + for line in input.readlines(): + strip = line.strip() + smi, name = parse_smiles_line(strip) + mol = Chem.MolFromSmiles(smi) + if mol != None: + i, best_tani = find_nearest(mol, ref_fps) + # the candidate molecule + print('%s\t%s' % (smi, name)) + # its molecular annotation + print('%s\t%s_T=%.2f' % (ref_smi[i], ref_names[i], best_tani)) + after = time.time() + dt = after - before + log('dt: %.2f' % dt) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_rotbond.py",".py","3918","112","#!/usr/bin/env python3 +# +# Copyright (C) 2023, Francois Berenger +# Tsuda laboratory, Tokyo University, +# 5-1-5 Kashiwa-no-ha, Kashiwa-shi, Chiba-ken, 277-8561, Japan. +# +# List rotatable bonds (RotBonds) found in a molecule's 3D conformer. +# Molecules are read from a .sdf file, so they are expected to be in 3D. +# There are two types of rotatable bonds: +# - those that can significantly change the conformation of a molecule +# - those that just make some hydrogens move +# (hydrogen(s) attached to a ""terminal"" heavy atom) +# We list them separately, because users might not be interested in trying +# to rotate all rotatable bonds. +# Output format is: +#--- +# ^TOTAL_ROT_BONDS:TER_ROT_BONDS:MOL_NAME$ +# ^REG i j$ # bond_type start_i stop_j +# ... +# ^TER k l$ +# ... +#--- + +import argparse, sys +from rdkit import Chem + +def already_protonated(mol): + before = mol.GetNumAtoms() + molH = Chem.AddHs(mol) + after = molH.GetNumAtoms() + return (before == after) + +def is_HA(a): + return (a.GetAtomicNum() != 1) + +def count_heavy_neighbors(a): + res = 0 + for n in a.GetNeighbors(): + if is_HA(n): + res += 1 + return res + +# N with valence 4 becomes N+ +def correct_N_formal_charge(mol): + for a in mol.GetAtoms(): + if a.GetAtomicNum() == 7 and \ + a.GetTotalValence() == 4 and \ + a.GetFormalCharge() != +1: + a.SetFormalCharge(1) + mol.UpdatePropertyCache() + Chem.SanitizeMol(mol) + return mol + +# a terminal heavy atom with at least one hydrogen attached +# a.GetTotalNumHs(includeNeighbors=True) avoids an rdkit bug +def is_hydrogenated_terminal(a): + return (is_HA(a) and \ + count_heavy_neighbors(a) == 1 and \ + a.GetTotalNumHs(includeNeighbors=True) >= 1) + +if __name__ == '__main__': + # CLI options parsing + parser = argparse.ArgumentParser(description = ""list rotatable bonds"") + parser.add_argument(""-i"", metavar = ""input.sdf"", dest = ""input_fn"", + help = ""3D conformer input file "") + # parse CLI --------------------------------------------------------------- + if len(sys.argv) == 1: + # user has no clue of what to do -> usage + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + # parse CLI end ----------------------------------------------------------- + # BUG IF removeHs=False; hydrogens are not properfly counted attached + # to heavy atoms in this case !!!!!!!!!!!!!!!! + # REPORTED on ML + for mol0 in Chem.SDMolSupplier(input_fn, removeHs=False, sanitize=False): + if mol0 == None: + assert(False) + # make rdkit robust to some stupid molecular errors + mol = correct_N_formal_charge(mol0) + name = mol.GetProp('_Name') + if not already_protonated(mol): + # a conformer for docking should have explicit hydrogens + print(""ERROR: not protonated: %s"" % name, file=sys.stderr) + # sys.exit(1) + reg_bonds = [] + ter_bonds = [] + # examine each bond + for b in mol.GetBonds(): + a_i = b.GetBeginAtom() + a_j = b.GetEndAtom() + i = a_i.GetIdx() + j = a_j.GetIdx() + ij = (i, j) + if is_HA(a_i) and is_HA(a_j) and \ + b.GetBondTypeAsDouble() == 1.0 and \ + not b.IsInRing(): + if is_hydrogenated_terminal(a_i) or \ + is_hydrogenated_terminal(a_j): + ter_bonds.append(ij) + else: + reg_bonds.append(ij) + num_reg_bonds = len(reg_bonds) + num_ter_bonds = len(ter_bonds) + total = num_reg_bonds + num_ter_bonds + print('%d:%d:%s' % (total, num_ter_bonds, name)) + for i, j in reg_bonds: + print('REG\t%d\t%d' % (i, j)) + for i, j in ter_bonds: + print('TER\t%d\t%d' % (i, j)) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc_frag2smi.py",".py","8757","224","#!/usr/bin/env python3 + +# Copyright (C) 2020, Francois Berenger +# Yamanishi laboratory, +# Department of Bioscience and Bioinformatics, +# Faculty of Computer Science and Systems Engineering, +# Kyushu Institute of Technology, +# 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan. + +# txt fragment to smi + +import argparse, rdkit, re, sys, time +import molenc_common as common +from rdkit import Chem +from rdkit.Chem import AllChem +from rdkit.Chem.Draw import rdMolDraw2D + +# ""#anchors:1"" +def read_anchors_header(line): + (anchors, nb_anchors) = [t(s) for t,s in + zip((str,int), re.split('[:]', line))] + assert(anchors == ""#anchors"") + return nb_anchors + +# ""0,6,2,0,0 0 0,6,2,0,0"" +def read_anchor(line): + (start_t, start_i, stop_t) = [t(s) for t,s in + zip((str,int,str), re.split('[ ]', line))] + return start_i + +def current_valence(a): + res = 0.0 + for b in a.GetBonds(): + bt = b.GetBondType() + if bt == rdkit.Chem.rdchem.BondType.SINGLE: + res += 1.0 + elif bt == rdkit.Chem.rdchem.BondType.AROMATIC: + res += 1.5 + elif bt == rdkit.Chem.rdchem.BondType.DOUBLE: + res += 2.0 + elif bt == rdkit.Chem.rdchem.BondType.TRIPLE: + res += 3.0 + return res + +def count_aromatic_bonds(a): + count = 0 + for b in a.GetBonds(): + if b.GetBondType() == rdkit.Chem.rdchem.BondType.AROMATIC: + count += 1 + return count + +# try to correct a molecule that failed kekulization +def restore_from_kekulization_error(mol): + print('---------', file=sys.stderr) + pat1 = Chem.MolFromSmarts('c(=O)') + rep1 = Chem.MolFromSmarts('c(O)') + res_mol1 = AllChem.ReplaceSubstructs(mol, pat1, rep1) + res_mol = res_mol1[0] + for a in res_mol.GetAtoms(): + anum = a.GetAtomicNum() + val = current_valence(a) + if anum == 7 and (not a.IsInRing()): + print('N not in ring with %d aromatic bonds; val=%.1f' % + (count_aromatic_bonds(a), val), file = sys.stderr) + if a.IsInRing() and anum == 7: + print('N in ring with %d aromatic bonds; val=%.1f' % + (count_aromatic_bonds(a), val), file = sys.stderr) + if val == 4.0: + # set the correct +1 partial charge + # for Nitrogen with valence 4 in rings + a.SetFormalCharge(1) + # forbid addition of implicit hydrogens later + a.SetNoImplicit(True) + a.SetNumExplicitHs(0) + print('N charge correct', file = sys.stderr) + # if count_aromatic_bonds(a) == 2 and val == 3.0: + # # aromatic Nitrogen _must_ be [nH] instead of [n] + # a.SetNumExplicitHs(1) + if count_aromatic_bonds(a) >= 1: + # aromatic Nitrogen _must_ be [nH] instead of [n] + a.SetNumExplicitHs(1) + # pat2 = Chem.MolFromSmarts('[n+0]') + # rep2 = Chem.MolFromSmarts('[nH]') + # res_mol2 = AllChem.ReplaceSubstructs(res_mol, pat2, rep2) + # res_mol = res_mol2[0] + return res_mol + +# create a fake molecule for the corresp. fragment +def read_one_fragment(input): + res_mol = Chem.RWMol() + atoms_header = input.readline().strip() + if atoms_header == '': + raise common.End_of_file # no EOF in Python... + nb_atoms, frag_name = common.read_atoms_header(atoms_header) + old2new = {} + # read atoms + for _i in range(nb_atoms): + line = input.readline().strip() + (index, nb_pi, atomic_num, nb_HA, charge, stereo) = \ + common.read_atom(line) + # add atom + a = Chem.Atom(atomic_num) + a.SetFormalCharge(charge) + if stereo > 0: # set chirality + a.SetChiralTag(common.atom_stereo_code_to_chiral_tag(stereo)) + j = res_mol.AddAtom(a) + # we will need to convert atom indexes later + old2new[index] = j + bonds_header = input.readline().strip() + nb_bonds = common.read_bonds_header(bonds_header) + stereo_bonds = [] + # read bonds + for i in range(nb_bonds): + line = input.readline().strip() + (start_i, bt, stop_i, (stereo, c, d)) = common.read_bond(line) + # convert atom indexes + start = old2new[start_i] + stop = old2new[stop_i] + # print('%d %d' % (start, stop)) + # add bond + n = res_mol.AddBond(start, stop, bt) + if stereo != rdkit.Chem.rdchem.BondStereo.STEREONONE: + bi = n - 1 + # if an exception is thrown here, it means + # this stereobond stereo atom is out of the fragments atoms + # (attachment points dummy atoms are forbidden) + # this should never happen since such bonds are protected during + # fragmentation + # + # convert stereo bond stereo atoms indexes + a = old2new[c] + b = old2new[d] + stereo_bonds.append((bi, stereo, a, b)) + anchors_header = input.readline().strip() + nb_anchors = read_anchors_header(anchors_header) + for _i in range(nb_anchors): + line = input.readline().strip() + anchor = read_anchor(line) + start = old2new[anchor] + # dandling attachment point: dummy atom + a = Chem.Atom('*') + j = res_mol.AddAtom(a) + # only single, non stereo, bonds out of rings have been cut + res_mol.AddBond(start, j, Chem.rdchem.BondType.SINGLE) + # all fragments atoms and internal bonds are here now + # so stereo bonds info can be set + # FBR: WARNING: just does not work... :( + # it seems that 'Chem.SanitizeMol(res_mol)' looses the stereo info + # reported on rdkit-users ML Fri Jan 15 11:49:46 JST 2021 + # print('before stereo: %s' % Chem.MolToSmiles(res_mol), file=sys.stderr) + for (bi, stereo, a, b) in stereo_bonds: + bond = res_mol.GetBondWithIdx(bi) + bond.SetStereoAtoms(a, b) + bond.SetStereo(stereo) + print('%s stereo %s on bond %d (%d, %d)' % + (frag_name, common.char_of_bond_stereo(stereo), bi, a, b), + file=sys.stderr) + # smi for mol + try: + Chem.SanitizeMol(res_mol) + Chem.AssignStereochemistry(res_mol) # ! MANDATORY; AFTER SanitizeMol ! + # print('after sanitize then stereo: %s' % Chem.MolToSmiles(res_mol), file=sys.stderr) + res_smi = Chem.MolToSmiles(res_mol) + return (False, res_smi, frag_name) + except rdkit.Chem.rdchem.KekulizeException: + print(""KekulizeException in %s"" % frag_name, file=sys.stderr) + return (True, """", frag_name) + # if kekul_error: + # res_mol = restore_from_kekulization_error(res_mol) + # try: + # Chem.SanitizeMol(res_mol) + # # print('restored one') + # except rdkit.Chem.rdchem.KekulizeException: + # print('kekulization rescue failed\n%s\t%s' % + # (Chem.MolToSmiles(res_mol), frag_name), file=sys.stderr) + # kekul_error2 = True + # ## draw mol with atom indexes for inspection + # # d = rdMolDraw2D.MolDraw2DCairo(500, 500) + # # d.drawOptions().addAtomIndices = True + # # d.DrawMolecule(res_mol) + # # d.FinishDrawing() + # # png_fn = '%s.png' % frag_name + # # with open(png_fn, 'wb') as fn: + # # fn.write(d.GetDrawingText()) + +if __name__ == '__main__': + before = time.time() + # CLI options parsing + parser = argparse.ArgumentParser(description = + ""convert txt fragments to SMILES"") + parser.add_argument(""-i"", metavar = ""input.frags"", dest = ""input_fn"", + help = ""fragments input file"") + parser.add_argument(""-o"", metavar = ""output.smi"", dest = ""output_fn"", + help = ""SMILES output file"") + # parse CLI + if len(sys.argv) == 1: + # user has no clue of how to use + parser.print_help(sys.stderr) + sys.exit(1) + args = parser.parse_args() + input_fn = args.input_fn + output = open(args.output_fn, 'w') + err_out = open(args.output_fn + '.err.names', 'w') + count = 0 + kekul_err_count = 0 + with open(input_fn) as input: + try: + while True: + kekul_err, smi, name = read_one_fragment(input) + count += 1 + if kekul_err: + print('%s' % name, file=err_out) + kekul_err_count += 1 + else: + print('%s\t%s' % (smi, name), file=output) + except common.End_of_file: + pass + after = time.time() + dt = after - before + print(""%d (%d kekul. errors) fragments at %.2f frag/s"" % + (count, kekul_err_count, count / dt), file=sys.stderr) + output.close() + err_out.close() +","Python" +"QSAR","UnixJunkie/molenc","bin/rgb_scale.py",".py","256","12","#!/usr/bin/env python3 + +# pip3 install colour # to get the required library + +from colour import Color + +red = Color(""red"") +colors = list(red.range_to(Color(""white""), 101)) +for c in colors: + (r, g, b) = c.get_rgb() + print(""%.2f %.2f %.2f"" % (r, g, b)) +","Python" +"QSAR","UnixJunkie/molenc","bin/molenc.sh",".sh","4171","160","#!/bin/bash + +#set -x # DEBUG +set -u + +if [ $# -eq 0 ]; then + echo ""usage:"" + echo ""molenc.sh -i input.smi -o output.txt"" + echo "" [-d encoding.dix]: reuse existing feature dictionary"" + echo "" [-r i:j]: fingerprint radius (default=0:1)"" + echo "" [--pairs]: use atom pairs instead of Faulon's FP"" + echo "" [-m ]: maximum allowed atom-pair distance"" + echo "" (default: no limit)"" + echo "" [--seq]: sequential mode (disable parallelization)"" + echo "" [-v]: debug mode; keep temp files"" + echo "" [-n ]: max jobs in parallel"" + echo "" [-c ]: chunk size"" + echo "" [--no-std]: don't standardize input file molecules"" + echo "" ONLY USE IF THEY HAVE ALREADY BEEN STANDARDIZED"" + exit 1 +fi + +input="""" +output="""" +dico="""" +range=""0:1"" # default val +no_std="""" +sequential="""" +debug="""" +nprocs=""1"" +csize=""1"" +pairs="""" +max_dist="""" + +# parse CLI options +while [[ $# -gt 0 ]]; do + key=""$1"" + case $key in + -i) + input=""$2"" + shift # skip option specifier + shift # skip option value + ;; + -o) + output=""$2"" + shift + shift + ;; + -d) + dico=""$2"" + shift + shift + ;; + -m) + max_dist=""$2"" + shift + shift + ;; + -n) + nprocs=""$2"" + shift + shift + ;; + -c) + csize=""$2"" + shift + shift + ;; + -r) + range=""$2"" + shift + shift + ;; + --no-std) + no_std=""TRUE"" + shift # past argument + ;; + --seq) + sequential=""TRUE"" + shift # past argument + ;; + --pairs) + pairs=""TRUE"" + shift # past argument + ;; + -v) + debug=""TRUE"" + shift # past argument + ;; + *) # unknown option + echo ""molenc: unknown option: ""$1 + exit 1 + ;; + esac +done + +std_log=$input'.std_log' +tmp=`mktemp` +tmp_smi=$tmp'_std.smi' +tmp_types=$tmp'_std.types' +tmp_enc=$tmp'_std.enc' + +# enable parallelization or not +there_is_pardi=`which pardi` +if [ ""$sequential"" != """" ]; then + there_is_pardi="""" +fi + +if [ ""$no_std"" == """" ]; then + # tell user how to install standardiser if not here + which standardiser 2>&1 > /dev/null || \ + echo 'molenc: ERROR: type: pip3 install chemo-standardizer' + if [ $nprocs -gt 1 ] && [ ""$there_is_pardi"" != """" ]; then + echo 'standardizing molecules in parallel...' + pardi -p -n $nprocs -i $input -o $tmp_smi -c 100 -d l -ie '.smi' -oe '.smi' \ + -w 'standardiser -i %IN -o %OUT 2>/dev/null' + else + echo 'standardizing molecules...' + (standardiser -i $input -o $tmp_smi 2>&1) > $std_log + fi +else + cp $input $tmp_smi +fi +if [ $nprocs -gt 1 ] && [ ""$there_is_pardi"" != """" ]; then + echo 'typing atoms in parallel...' + pardi -p -n $nprocs -i $tmp_smi -o $tmp_types -c 100 -d l -ie '.smi' \ + -w 'molenc_type_atoms.py -i %IN -o %OUT 2>/dev/null' +else + echo 'typing atoms...' + molenc_type_atoms.py -i $tmp_smi -o $tmp_types +fi + +echo ""encoding molecules..."" +if [ ""$pairs"" != """" ]; then + if [ ""$max_dist"" != """" ]; then + max_dist=""-m ""$max_dist + fi + if [ ""$dico"" != """" ]; then + molenc_ap -np $nprocs -cs $csize -i $tmp_types -o $output -id $dico \ + $max_dist + else + molenc_ap -np $nprocs -cs $csize -i $tmp_types -o $output \ + -od $input'.dix' $max_dist + fi +else + if [ ""$dico"" != """" ]; then + # if dictionary is provided, parallelize encoding + molenc_e -n $nprocs -i $tmp_types -r $range -o $tmp_enc -d $dico + molenc_d -n $nprocs -i $tmp_enc -o $output -d $dico + else + molenc_e -i $tmp_types -r $range -o $tmp_enc + molenc_d -i $tmp_enc -o $output + fi +fi + +# cleanup +if [ ""$debug"" == """" ]; then + rm -f $std_log $tmp $tmp_smi $tmp_types $tmp_enc +fi +","Shell" +"QSAR","UnixJunkie/molenc","src/gen_bindings.sh",".sh","426","12","#!/bin/bash + +# pyml_bindgen rdkit_wrapper_specs.txt rdkit_wrapper Rdkit \ +# --caml-module=Rdkit --of-pyo-ret-type=no_check > rdkit.ml + +pyml_bindgen rdkit_wrapper_specs.txt rdkit_wrapper Rdkit \ + --embed-python-source rdkit_wrapper.py \ + --caml-module=Rdkit --of-pyo-ret-type=no_check > rdkit.ml + +# format the generated code +ocamlformat --inplace --enable-outside-detected-project rdkit.ml +","Shell" +"QSAR","UnixJunkie/molenc","src/rdkit_wrapper.py",".py","9311","259"," +import rdkit, random, re, sys, typing +from rdkit import Chem +import numpy as np + +def nb_heavy_atom_neighbors(a: rdkit.Chem.rdchem.Atom) -> int: + res = 0 + for neighb in a.GetNeighbors(): + if neighb.GetAtomicNum() > 1: + res += 1 + return res + +# return (#HA, #H) +def count_neighbors(a: rdkit.Chem.rdchem.Atom) -> tuple[int, int]: + nb_heavy = nb_heavy_atom_neighbors(a) + nb_H = a.GetTotalNumHs() + return (nb_heavy, nb_H) + +# # DeepSMILES: no rings neither branches opening/closing +# to_deep_smiles = deepsmiles.Converter(rings=True, branches=True) + +# # space-separate all DeepSMILES tokens corresponding to given SMILES +# def tokenize_one(smi: str) -> str: +# assert(smi.find('.') == -1) # enforce standardization/salt removal +# mol = Chem.MolFromSmiles(smi) +# # don't canonicalize: the input SMILES might have been randomized on purpose +# protected_smi = Chem.MolToSmiles(mol, allHsExplicit=True, canonical=False) +# protected_dsmi = to_deep_smiles.encode(protected_smi) +# # print(""pdsmi: '%s'"" % protected_dsmi) +# # space before [ and after ] +# pdsmi = re.sub(r""(\[[^\]]+\])"", r"" \1 "", protected_dsmi) +# # space before % +# pdsmi = pdsmi.replace('%', ' %') +# # protect branch closings (no branch openings in DeepSMILES) +# pdsmi = pdsmi.replace(')', ' ) ') +# # protect bonds +# pdsmi = pdsmi.replace('-', ' - ') +# # protect - when it is a formal charge +# pdsmi = re.sub(' - (\d)\]', '-\1]', pdsmi) +# pdsmi = re.sub(' - \]', '-]', pdsmi) +# pdsmi = pdsmi.replace('=', ' = ') +# pdsmi = pdsmi.replace('#', ' # ') +# pdsmi = pdsmi.replace('$', ' $ ') +# pdsmi = pdsmi.replace(':', ' : ') +# # protect long numbers (prefixed by % in SMILES) +# pdsmi = re.sub(r""%(\d)(\d)"", r"" %\1\2 "", pdsmi) +# # single digit numbers are separate words +# pdsmi = re.sub(r"" (\d)(\d)"", r"" \1 \2"", pdsmi) +# # protect stereo bonds +# pdsmi = pdsmi.replace(""/"", "" / "") +# pdsmi = pdsmi.replace(""\\"", "" \\ "") +# # several spaces to one +# pdsmi = re.sub('[ ]+', ' ', pdsmi) +# # rm leading/trailing whitespaces +# pdsmi = pdsmi.strip() +# # print(""pdsmi: '%s'"" % pdsmi) +# return pdsmi + +def random_reorder_atoms(mol: rdkit.Chem.rdchem.Mol): + rand_order = list(range(mol.GetNumAtoms())) + random.shuffle(rand_order) + rand_mol = Chem.RenumberAtoms(mol, newOrder=rand_order) + return rand_mol + +# return n random versions of smi +def smi_randomize(smi: str, n: int, seed: int) -> list[str]: + res = [] + mol = Chem.MolFromSmiles(smi) + random.seed(seed) + for i in range(n): + rand_mol = random_reorder_atoms(mol) + rand_smi = Chem.MolToSmiles(rand_mol, canonical=False) + res.append(rand_smi) + return res + +# encode by an integer what kind of ring this atom is involved in +def ring_membership(a): + if a.IsInRing(): + if a.GetIsAromatic(): + return 2 # in aromatic ring + else: + return 1 # in aliphatic ring + else: + return 0 # not in ring + +class Rdkit: + # this is needed because the OCaml side want to know how + # to get an object of type t + def __init__(self, smi: str): + self.mol = Chem.MolFromSmiles(smi) + self.mat = Chem.GetDistanceMatrix(self.mol) + + def add_hydrogens(self): + self.mol = Chem.AddHs(self.mol) + self.mat = Chem.GetDistanceMatrix(self.mol) + return self + + # (atomic_num, #HA, #H, valence - #H, formal_charge) + def type_atom(self, i: int) -> list[int]: + a = self.mol.GetAtomWithIdx(i) + anum = a.GetAtomicNum() + # do this on the ocaml side, since we get anum + # assert(anum > 1) # we want to consider only heavy atoms + nb_HA, nb_H = count_neighbors(a) + valence = a.GetTotalValence() + HA_used_val = valence - nb_H + formal_charge = a.GetFormalCharge() + return [anum, nb_HA, nb_H, HA_used_val, formal_charge] + + # new (2023) atom typing scheme + def type_EltFCaroNeighbs(self, i: int) -> list[int]: + a = self.mol.GetAtomWithIdx(i) + anum = a.GetAtomicNum() + fc = a.GetFormalCharge() + aro = ring_membership(a) + # count direct neighbors + nb_other = 0 # unsupported atoms + nb_C = 0 + nb_H = a.GetTotalNumHs() + nb_N = 0 + nb_O = 0 + nb_P = 0 + nb_S = 0 + nb_F = 0 + nb_Cl = 0 + nb_Br = 0 + nb_I = 0 + for neighb in a.GetNeighbors(): + x = neighb.GetAtomicNum() + if x > 1: # Hs already counted before (including implicits) + if x == 6: + nb_C += 1 + elif x == 7: + nb_N += 1 + elif x == 8: + nb_O += 1 + elif x == 15: + nb_P += 1 + elif x == 16: + nb_S += 1 + elif x == 9: + nb_F += 1 + elif x == 17: + nb_Cl += 1 + elif x == 35: + nb_Br += 1 + elif x == 53: + nb_I += 1 + else: + print(""WARN: unsupported anum: %d"" % x, file=sys.stderr) + nb_other += 1 + return [anum, fc, aro, nb_other, nb_C, nb_H, nb_N, nb_O, nb_P, nb_S, nb_F, nb_Cl, nb_Br, nb_I] + + # simpler atom typing scheme, to reduce the dimension of fingerprints, if needed + def type_atom_simple(self, i: int) -> list[int]: + a = self.mol.GetAtomWithIdx(i) + anum = a.GetAtomicNum() + fc = a.GetFormalCharge() + aro = ring_membership(a) + heavies, hydrogens = count_neighbors(a) + return [anum, fc, aro, heavies, hydrogens] + + # Daylight atom type (cf. ""atomic invariants"" in ""Extended-Connectivity Fingerprints"" paper + # by Rogers and Hahn from JCIM 2010; https://doi.org/10.1021/ci100050t. + # WARNING: this atom type is only defined for heavy atoms + # WARNING: the molecule must have hydrogens + def daylight_type_heavy_atom(self, i: int) -> list[int]: + a = self.mol.GetAtomWithIdx(i) + # heavy neighbors + heavies, hydrogens = count_neighbors(a) + # valence minus hydrogens + valence = a.GetTotalValence() + HA_used_val = valence - hydrogens + # atomic num. + anum = a.GetAtomicNum() + assert(anum > 1) # not supposed to be called on H; cf. warnings above + # formal charge + formal_charge = a.GetFormalCharge() + # hydrogens + # in ring + in_ring = int(a.IsInRing()) + return [anum, heavies, hydrogens, HA_used_val, formal_charge, in_ring] + + # # pyml_bindgen doesn't support list of tuples or even tuples... + # # type each atom of the molecule + # def type_atoms(self): + # res = [] + # for a in self.mol.GetAtoms(): + # res.append(type_atom(a)) + # return res + + def get_num_atoms(self) -> int: + return len(self.mat) + + # molecular graph diameter + def get_diameter(self) -> int: + return int(np.max(self.mat)) + + # get the distance (in bonds) between a pair of atoms + def get_distance(self, i: int, j: int) -> int: + return int(self.mat[i][j]) + + # distances (in bonds) from atom [i] to all other atoms in molecule + def get_distances(self, i: int) -> list[int]: + return list(map(lambda x: int(x), self.mat[i])) + + # chemical element of each atom in the molecule + def get_elements(self) -> list[str]: + res = [] + for a in self.mol.GetAtoms(): + res.append(a.GetSymbol()) + return res + + # atomic numbers of each atom in the molecule + def get_anums(self) -> list[int]: + res = [] + for a in self.mol.GetAtoms(): + res.append(a.GetAtomicNum()) + return res + + # # seed: random_seed + # # n: number of randomized SMILES to use + # # randomize: boolean + # # smi: SMILES to work on + # def get_deep_smiles(self, seed: int, n: int, randomize: bool, smi: str) -> list[str]: + # if n > 1: + # rand_smiles = smi_randomize(smi, n, seed) + # res = list(map(tokenize_one, rand_smiles)) + # return res + # else: + # rand_smi = smi + # if randomize: + # rand_smi = smi_randomize(smi, 1, seed)[0] + # return [tokenize_one(rand_smi)] + +# # tests +# m = Chem.MolFromSmiles('c1ccccc1') +# assert(get_distances(m) == [(0, 1, 1), +# (0, 2, 2), +# (0, 3, 3), +# (0, 4, 2), +# (0, 5, 1), +# (1, 2, 1), +# (1, 3, 2), +# (1, 4, 3), +# (1, 5, 2), +# (2, 3, 1), +# (2, 4, 2), +# (2, 5, 3), +# (3, 4, 1), +# (3, 5, 2), +# (4, 5, 1)]) +# assert(type_atoms(m) == [(6, 2, 1, 3, 0), +# (6, 2, 1, 3, 0), +# (6, 2, 1, 3, 0), +# (6, 2, 1, 3, 0), +# (6, 2, 1, 3, 0), +# (6, 2, 1, 3, 0)]) +","Python" +"QSAR","nadinulrich/log_P_prediction","Exporing_chemical_datasets_DNN_log_P.py",".py","8884","203","#Copyright 2017 PandeLab + +#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), +# to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +#THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +import tensorflow as tf +import numpy as np +import deepchem as dc +from deepchem.feat.mol_graphs import ConvMol +from deepchem.metrics import to_one_hot +from deepchem.models import TensorGraph +from deepchem.models.tensorgraph.layers import L2Loss +from deepchem.models.tensorgraph.layers import Feature, GraphConv, BatchNorm, GraphPool, Dense, Dropout, GraphGather, \ + SoftMax, \ + Label, SoftMaxCrossEntropy, Weights, WeightedError, Stack +import csv + +#Reads data and converts data to ConvMol objects + +def read_data(input_file_path): + featurizer = dc.feat.ConvMolFeaturizer(use_chirality=True) + loader = dc.data.CSVLoader(tasks=prediction_tasks, smiles_field=""SMILES"", featurizer=featurizer) + dataset = loader.featurize(input_file_path, shard_size=8192) + # Initialize transformers + transformer = dc.trans.NormalizationTransformer(transform_w=True, dataset=dataset) + print(""About to transform data"") + dataset = transformer.transform(dataset) + + return dataset + +#Generation of batches from the data as input in network + +def default_generator(dataset, + epochs=1, + batch_size=50, + predict=False, + deterministic=True, + pad_batches=True, + labels=None, + weights=None, + atom_features=None, + degree_slice=None, + membership=None, + deg_adjs=None): + for epoch in range(epochs): + print('Epoch number:', epoch) + for ind, (X_b, y_b, w_b, ids_b) in enumerate( + dataset.iterbatches( + batch_size, + pad_batches=pad_batches, + deterministic=deterministic)): + d = {} + + for i, label in enumerate(labels): + d[label] = np.expand_dims(y_b[:, i],1) + d[weights] = w_b + multiConvMol = ConvMol.agglomerate_mols(X_b) + d[atom_features] = multiConvMol.get_atom_features() + d[degree_slice] = multiConvMol.deg_slice + d[membership] = multiConvMol.membership + for i in range(1, len(multiConvMol.get_deg_adjacency_lists())): + d[deg_adjs[i - 1]] = multiConvMol.get_deg_adjacency_lists()[i] + yield d + +#Used for loading of trained model + +def layer_reference(model, layer): + if isinstance(layer, list): + return [model.layers[x.name] for x in layer] + return model.layers[layer.name] + +#Get array for the calculation of rms and r² for dataset +def reshape_y_pred(y_true, y_pred): + + n_samples = len(y_true) + retval = np.vstack(y_pred) + return retval[:n_samples] + +#Define working directory + +model_dir = working_directory + +#Define prediction task and directory of .csv file +#csv file should include SMILES and the prediction task + +prediction_tasks = ['logP'] +train_dataset, test_dataset = read_data(data_directory) + +#Define model, batch size, learning rate + +model = TensorGraph(tensorboard=True, + batch_size=50, + learning_rate=0.0001, + use_queue=False, + model_dir=model_dir) +#Placeholders for the chemical structures +#Chirality is used; if chirality should not be used: atom_features = Feature(shape=(None, 75)) +atom_features = Feature(shape=(None, 78)) +degree_slice = Feature(shape=(None, 2), dtype=tf.int32) +membership = Feature(shape=(None,), dtype=tf.int32) +deg_adjs = [] + +#Define structure of neural network + +for i in range(0, 10 + 1): + deg_adj = Feature(shape=(None, i + 1), dtype=tf.int32) + deg_adjs.append(deg_adj) +#Input +in_layer = atom_features +#Layer 1 +for layer_size in [64, 64]: + gc1_in = [in_layer, degree_slice, membership] + deg_adjs + gc1 = GraphConv(layer_size, activation_fn=tf.nn.relu, in_layers=gc1_in) + batch_norm1 = BatchNorm(in_layers=[gc1]) + gp_in = [batch_norm1, degree_slice, membership] + deg_adjs + in_layer1 = GraphPool(in_layers=gp_in) +#Layer 2 +for layer_size in [128, 128]: + gc2_in = [in_layer1, degree_slice, membership] + deg_adjs + gc2 = GraphConv(layer_size, activation_fn=tf.nn.relu, in_layers=gc2_in) + batch_norm2 = BatchNorm(in_layers=[gc2]) + gp2_in = [batch_norm2, degree_slice, membership] + deg_adjs + in_layer2 = GraphPool(in_layers=gp2_in) +dense = Dense(out_channels=256, activation_fn=tf.nn.relu, in_layers=[in_layer2]) +batch_norm3 = BatchNorm(in_layers=[dense]) +batch_norm3 = Dropout(0.1, in_layers=[batch_norm3]) +readout = GraphGather( + batch_size=50, + activation_fn=tf.nn.tanh, + in_layers=[batch_norm3, degree_slice, membership] + deg_adjs) +costs = [] +labels = [] +regression = Dense( out_channels=1, activation_fn=None, in_layers=[readout]) +model.add_output(regression) +label = Label(shape=(None, 1)) +labels.append(label) +cost = L2Loss(in_layers=[label, regression]) +costs.append(cost) +all_cost = Stack(in_layers=costs, axis=1) +weights = Weights(shape=(None, len(prediction_tasks))) +loss = WeightedError(in_layers=[all_cost, weights]) +model.set_loss(loss) + +#Define Training of neural network and the number of epochs for training +gene = default_generator(train_dataset, epochs=60, predict=True, pad_batches=True, + labels=labels, weights=weights, atom_features=atom_features, degree_slice=degree_slice, + membership=membership, deg_adjs=deg_adjs) +model.fit_generator(gene) +model.save() + +#Predict with model +#Load the model, which was previously trained +model2 = TensorGraph.load_from_dir(model.model_dir) +gene = default_generator(train_dataset, epochs=1, predict=True, pad_batches=True, + labels=labels, weights=weights, atom_features=atom_features, degree_slice=degree_slice, + membership=membership, deg_adjs=deg_adjs) +labels = layer_reference(model2, labels) +weights = layer_reference(model2, weights) +atom_features = layer_reference(model2, atom_features) +degree_slice = layer_reference(model2, degree_slice) +membership = layer_reference(model2, membership) +deg_adjs = layer_reference(model2, deg_adjs) +#Load the train_dataset for evaluation +gene = default_generator(train_dataset, epochs=1, predict=True, pad_batches=True, + labels=labels, weights=weights, atom_features=atom_features, degree_slice=degree_slice, + membership=membership, deg_adjs=deg_adjs) +#Load the test_dataset for evaluation +gene1 = default_generator(test_dataset, epochs=1, predict=True, pad_batches=True, + labels=labels, weights=weights, atom_features=atom_features, degree_slice=degree_slice, + membership=membership, deg_adjs=deg_adjs) + +metric = dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode = ""regression"") +rms=dc.metrics.Metric(dc.metrics.rms_score,np.mean,mode='regression') + +#Check performance on the training-dataset + +print(""Evaluating on train data"") +train_predictions = model2.predict_on_generator(gene) +train_predictions = reshape_y_pred(train_dataset.y,train_predictions) +train_scores = metric.compute_metric(train_dataset.y, train_predictions,train_dataset.w) +train_scores2 = rms.compute_metric(train_dataset.y, train_predictions, train_dataset.w) +print(""Train r²: %f"" % train_scores) +print(""Train rms: %f"" % train_scores2) + +#Check performance on the test_dataset + +print(""Evaluating on test data"") +test_predictions = model2.predict_on_generator(gene1) +test_predictions = reshape_y_pred(test_dataset.y, test_predictions) +test_scores = metric.compute_metric(test_dataset.y, test_predictions, test_dataset.w) +test_scores2 = rms.compute_metric(test_dataset.y, test_predictions, test_dataset.w) +print(""Test r²: %f"" % test_scores) +print(""Test rms: %f"" % test_scores2) + +","Python"