Datasets:
Delete processing
Browse filesFiles changed (7)
- processing/dmgi_model.pyDeleted-103
- processing/graph_embedding.pyDeleted-71
- processing/npy_to_h5.pyDeleted-28
- processing/pretrain_dmgi.pyDeleted-77
- processing/selfies_embedding.pyDeleted-39
- processing/smiles_to_selfies.pyDeleted-52
- processing/text_embedding.pyDeleted-96
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import torchimport torch.nn.functional as F
import torch_geometric.transforms as Tfrom torch_geometric.nn import GCNConv
def load_heterodata(path): data = torch.load(path, map_location=torch.device('cpu'))
print("Available edge types in the dataset:", data.edge_types) # data['Compound'].train_mask = torch.zeros(data['Compound'].num_nodes, dtype=torch.bool) # data['Compound'].val_mask = torch.zeros(data['Compound'].num_nodes, dtype=torch.bool) # data['Compound'].test_mask = torch.zeros(data['Compound'].num_nodes, dtype=torch.bool)
# train_indices = np.random.choice(data['Compound'].num_nodes, int(data['Compound'].num_nodes * 0.8), replace=False) # val_indices = np.random.choice(np.setdiff1d(np.arange(data['Compound'].num_nodes), train_indices), int(data['Compound'].num_nodes * 0.1), replace=False) # test_indices = np.setdiff1d(np.arange(data['Compound'].num_nodes), np.concatenate([train_indices, val_indices]))
# data['Compound'].train_mask[train_indices] = 1 # data['Compound'].val_mask[val_indices] = 1 # data['Compound'].test_mask[test_indices] = 1
# print(f'Train node count: {data["Compound"].train_mask.sum()}') # print(f'Val node count: {data["Compound"].val_mask.sum()}') # print(f'Test node count: {data["Compound"].test_mask.sum()}')
metapaths = [ [('Compound', 'CTI', 'Protein'), ('Protein', 'rev_CTI', 'Compound')], [('Drug', 'DTI', 'Protein'), ('Protein', 'rev_DTI', 'Drug')], [('Protein', 'PPI', 'Protein'), ('Protein', 'rev_PPI', 'Protein')], [('Gene', 'Orthology', 'Gene'), ('Gene', 'rev_Orthology', 'Gene')], ] print(metapaths) data = T.AddMetaPaths(metapaths, drop_orig_edge_types=True)(data) print('Available edge types in the dataset after adding metapaths:', data.edge_types)
return data
class DMGI(torch.nn.Module): def __init__(self, num_nodes, in_channels, out_channels, num_relations): super().__init__() self.convs = torch.nn.ModuleList( [GCNConv(in_channels, out_channels) for _ in range(num_relations)]) self.M = torch.nn.Bilinear(out_channels, out_channels, 1) self.Z = torch.nn.Parameter(torch.empty(num_nodes, out_channels)) self.reset_parameters()
def reset_parameters(self): for conv in self.convs: conv.reset_parameters() torch.nn.init.xavier_uniform_(self.M.weight) self.M.bias.data.zero_() torch.nn.init.xavier_uniform_(self.Z)
def forward(self, x, edge_indices): pos_hs, neg_hs, summaries = [], [], [] for conv, edge_index in zip(self.convs, edge_indices): pos_h = F.dropout(x, p=0.5, training=self.training) pos_h = conv(pos_h, edge_index).relu() pos_hs.append(pos_h)
neg_h = F.dropout(x, p=0.5, training=self.training) neg_h = neg_h[torch.randperm(neg_h.size(0), device=neg_h.device)] neg_h = conv(neg_h, edge_index).relu() neg_hs.append(neg_h)
summaries.append(pos_h.mean(dim=0, keepdim=True))
return pos_hs, neg_hs, summaries
def loss(self, pos_hs, neg_hs, summaries): loss = 0. for pos_h, neg_h, s in zip(pos_hs, neg_hs, summaries): s = s.expand_as(pos_h) loss += -torch.log(self.M(pos_h, s).sigmoid() + 1e-15).mean() loss += -torch.log(1 - self.M(neg_h, s).sigmoid() + 1e-15).mean()
pos_mean = torch.stack(pos_hs, dim=0).mean(dim=0) neg_mean = torch.stack(neg_hs, dim=0).mean(dim=0)
pos_reg_loss = (self.Z - pos_mean).pow(2).sum() neg_reg_loss = (self.Z - neg_mean).pow(2).sum() loss += 0.001 * (pos_reg_loss - neg_reg_loss)
return loss
def load_dmgi_model(path, data): model = DMGI(data['Compound'].num_nodes, data['Compound'].x.size(-1), 64, len(data.edge_types)) model.load_state_dict(torch.load(path)) return model1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071import osimport pandas as pdimport numpy as npimport torchimport timefrom datetime import datetimefrom unimol_tools import UniMolRepr
unimol_model = UniMolRepr(data_type='molecule', remove_hs=False, use_gpu=True)
def get_unimol_embeddings_batch(smiles_list, model): try: batch_repr = model.get_repr(smiles_list, return_atomic_reprs=True) cls_reprs = batch_repr['cls_repr'] return np.array(cls_reprs) except Exception as e: print(f"Error embedding batch: {e}") return None
def process_folder_unimol(folder_path, batch_size=2000): """ Walk through the folder and process each CSV file ending with 'filtered'. Embeddings are saved in the same folder with '_graph_embedding.npy' added to the filename. """ for root, dirs, files in os.walk(folder_path): for file in files: if not file.endswith("filtered.csv") and not file.endswith("mock.csv"): file_path = os.path.join(root, file) print(f"Processing file: {file_path}") try: df = pd.read_csv(file_path) column_name = 'smiles' if column_name not in df.columns: column_name = 'mol'
if column_name not in df.columns: raise ValueError("'smiles' column not found in the CSV file.")
df = df.dropna(subset=[column_name]) smiles_list = df[column_name].tolist() print(f"Found {len(smiles_list)} valid SMILES to process.")
all_embeddings = [] for i in range(0, len(smiles_list), batch_size): batch = smiles_list[i:i+batch_size] embeddings = get_unimol_embeddings_batch(batch, unimol_model) if embeddings is not None: all_embeddings.append(embeddings) else: print(f"Warning: Batch {i//batch_size} failed.")
if all_embeddings: final_embeddings = np.concatenate(all_embeddings) output_file = os.path.join(root, f"{os.path.splitext(file)[0]}_graph_embedding.npy") np.save(output_file, final_embeddings) print(f"Saved embeddings with shape {final_embeddings.shape} to {output_file}\n") else: print(f"No embeddings generated for {file_path}.")
except Exception as e: print(f"Failed to process {file_path}: {e}\n")
folder_path = "/home/g3-bbm-project/main_folder/FineTune/finetune_data_multi/finetuning_datasets/classification" # Set your top-level folder hereprint(f"Starting UniMol embedding processing at {datetime.now().strftime('%H:%M:%S')}")start_time = time.time()
process_folder_unimol(folder_path)
total_time = time.time() - start_timeprint(f"\nTotal execution time: {total_time:.2f} seconds")print(f"Finished at {datetime.now().strftime('%H:%M:%S')}")12345678910111213141516171819202122232425262728import numpy as npimport h5pyimport argparseimport os
"""Example usage:python convert_npy_to_h5.py /path/to/input_file.npy /path/to/output_file.h5"""
def convert_npy_to_h5(npy_file_path, h5_output_path): if not os.path.isfile(npy_file_path): print(f"Error: Input file '{npy_file_path}' does not exist.") return
data = np.load(npy_file_path)
with h5py.File(h5_output_path, 'w') as h5_file: h5_file.create_dataset('data', data=data) print(f"Data from '{npy_file_path}' has been successfully saved to '{h5_output_path}'.")
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert a .npy file to a .h5 file.") parser.add_argument("npy_file", type=str, help="Path to the input .npy file.") parser.add_argument("h5_file", type=str, help="Path to the output .h5 file.")
args = parser.parse_args() convert_npy_to_h5(args.npy_file, args.h5_file)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import os
import numpy as np
import torchfrom torch.optim import Adamfrom torch_geometric import seed_everything
from dmgi_model import load_heterodata, DMGI
from datetime import datetime
# set random seedsseed_everything(42)np.random.seed(42)
torch.set_num_threads(5)
import argparse
parser = argparse.ArgumentParser()parser.add_argument('--data', default='/home/g3bbmproject/main_folder/KG/kg.pt/selformerv2_kg_heterodata_1224.pt')
args = parser.parse_args()
def train(data, model, optimizer): model.train() optimizer.zero_grad() x = data['Compound'].x edge_indices = data.edge_index_dict.values() pos_hs, neg_hs, summaries = model(x, edge_indices) loss = model.loss(pos_hs, neg_hs, summaries) loss.backward() optimizer.step() return float(loss)
def pretrain_dmgi(hps, data, device): model = DMGI(data['Compound'].num_nodes, data['Compound'].x.size(-1), hps[0], len(data.edge_types)) data, model = data.to(device), model.to(device) print(data.node_types) # Print available edge types in the dataset print("Available edge types in the dataset:", data.edge_types)
optimizer = Adam(model.parameters(), lr=hps[1], weight_decay=hps[2])
for epoch in range(1, 101): epoch_start = datetime.now() train_loss = train(data, model, optimizer) if epoch == 1 or epoch % 25 == 0: print(f'\tEpoch: {epoch:03d}, Loss: {train_loss:.4f}, Time: {datetime.now() - epoch_start}')
return train_loss, model
if __name__ == '__main__': data = load_heterodata(args.data) print(f'Loaded data: {args.data}') device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print(f'\nUsing device: {device}\n')
print('Starting training...\n') train_start = datetime.now() loss, model = pretrain_dmgi([32, 0.01, 0.001], data, device) print(f'\nDone. Total training time: {datetime.now() - train_start}') # save model os.makedirs('models', exist_ok=True) torch.save(model.state_dict(), 'data/pretrained_models/kg_dmgi_model.pt') print(f'Model saved: data/pretrained_models/kg_dmgi_model.pt\n')123456789101112131415161718192021222324252627282930313233343536373839import osimport pandas as pdfrom pandarallel import pandarallelfrom transformers import RobertaTokenizer, RobertaModel, RobertaConfigimport torch
os.environ["TOKENIZERS_PARALLELISM"] = "false"os.environ["WANDB_DISABLED"] = "true"os.environ["CUDA_VISIBLE_DEVICES"] = "0"
SELFIES_DATASET_PATH = "data/temp_selfies.csv" # path to the SELFIES datasetMODEL_FILE_PATH = "data/pretrained_models/SELFormer" # path to the pre-trained SELFormer modelOUTPUT_EMBEDDINGS_PATH = "data/embeddings.csv" # path to save the generated embeddings
df = pd.read_csv(SELFIES_DATASET_PATH) # load the datasetprint(f"Loaded dataset with {len(df)} molecules.")
config = RobertaConfig.from_pretrained(MODEL_FILE_PATH) # load the pre-trained model and tokenizerconfig.output_hidden_states = Truetokenizer = RobertaTokenizer.from_pretrained("data/RobertaFastTokenizer")model = RobertaModel.from_pretrained(MODEL_FILE_PATH, config=config)
def get_sequence_embeddings(selfies): token = torch.tensor([tokenizer.encode(selfies, add_special_tokens=True, max_length=512, padding=True, truncation=True)]) # tokenize the SELFIES string output = model(token) # forward pass through the model sequence_out = output[0] # extract the sequence output and compute the mean pooling return torch.mean(sequence_out[0], dim=0).tolist()
print("Generating embeddings...")pandarallel.initialize(nb_workers=5, progress_bar=True)df["sequence_embeddings"] = df.selfies.parallel_apply(get_sequence_embeddings)
df.drop(columns=["selfies"], inplace=True)df.to_csv(OUTPUT_EMBEDDINGS_PATH, index=False)print(f"Embeddings saved to {OUTPUT_EMBEDDINGS_PATH}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import pandas as pdfrom pandarallel import pandarallelimport selfies as sf
def to_selfies(smiles): """ Converts SMILES to SELFIES representation. If an error occurs, returns the original SMILES unchanged. """ try: return sf.encoder(smiles) except sf.EncoderError: print(f"EncoderError for SMILES: {smiles}") return smiles
def prepare_data(path, save_to): """ Reads a dataset with SMILES, converts SMILES to SELFIES, and saves the result. """ chembl_df = pd.read_csv(path, sep="\t") chembl_df["selfies"] = chembl_df["canonical_smiles"] # Copy the SMILES column
pandarallel.initialize() chembl_df["selfies"] = chembl_df["selfies"].parallel_apply(to_selfies) chembl_df.drop(chembl_df[chembl_df["canonical_smiles"] == chembl_df["selfies"]].index, inplace=True) chembl_df.drop(columns=["canonical_smiles"], inplace=True) chembl_df.to_csv(save_to, index=False)
input_csv_path = "/home/g3bbmproject/main_folder/KG/kg.pt/our_10k_matched_data_with_embeddings.csv"output_csv_path = "data_with_selfies.csv"temp_smiles_path = "temp_smiles.csv"temp_selfies_path = "temp_selfies.csv"
data = pd.read_csv(input_csv_path)
# Save the SMILES column to a temporary file for conversiondata[['smiles']].rename(columns={"smiles": "canonical_smiles"}).to_csv(temp_smiles_path, index=False, sep="\t")
# Convert SMILES to SELFIES using the prepare_data functionprepare_data(path=temp_smiles_path, save_to=temp_selfies_path)
# Load the resulting SELFIES dataselfies_data = pd.read_csv(temp_selfies_path)
# Add the SELFIES column back to the original datadata['selfies'] = selfies_data['selfies'] # Assumes the converted file has a 'selfies' column
# Save the updated data to a new CSV filedata.to_csv(output_csv_path, index=False)
print(f'Total length of data: {len(data)}')print(f"Updated dataset with SELFIES saved to: {output_csv_path}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import osimport pandas as pdimport torchimport numpy as npfrom transformers import AutoTokenizer, AutoModelfrom tqdm import tqdm
# Check for GPU availabilitydevice = torch.device("cuda:2" if torch.cuda.is_available() else "cpu")print(f"Using device: {device}")
# Load SciBERT tokenizer and modelscibert_tokenizer = AutoTokenizer.from_pretrained("allenai/scibert_scivocab_uncased")scibert_model = AutoModel.from_pretrained("allenai/scibert_scivocab_uncased").to(device)scibert_model.eval() # Set the model to evaluation mode
# Function to generate text embeddings for a single textdef get_text_embeddings(text, tokenizer, model, device): if isinstance(text, str) and text.strip() != "": tokens = tokenizer.encode( text, add_special_tokens=True, max_length=512, padding=True, truncation=True, return_tensors="pt" ).to(device) with torch.no_grad(): output = model(tokens) text_out = output[0][0].mean(dim=0) else: text_out = torch.zeros(768).to(device) return text_out.cpu().numpy()
# New function: Process all CSV files ending with 'filtered' in a folder and its subfoldersdef process_folder(folder_path): """ Walk through the folder and process each CSV file ending with 'filtered'. Embeddings are saved in the same folder with '_text_embedding.npy' added to the base filename. """ for root, dirs, files in os.walk(folder_path): for file in files: if file.endswith("filtered.csv"): filtered_path = os.path.join(root, file) base_filename = file.replace("_filtered", "") full_path = os.path.join(root, base_filename)
if not os.path.exists(full_path): print(f"Corresponding full CSV file not found for {filtered_path}, skipping.\n") continue
print(f"Processing file: {filtered_path}")
try: # Read both full and filtered CSV files df_full = pd.read_csv(full_path) df_filtered = pd.read_csv(filtered_path)
'''if ("smiles" not in df_full.columns or "smiles" not in df_filtered.column): raise ValueError("'smiles' column not found in one of the CSV files.")
if "Description" not in df_filtered.columns: raise ValueError("'Description' column not found in filtered CSV file.")'''
# Map smiles to description
column_name = 'smiles' if base_filename == 'bace': column_name = 'mol'
smiles_to_description = dict(zip(df_filtered["smiles"], df_filtered["Description"]))
# Prepare Description column for full df (may include Nones) df_full["Description"] = df_full[column_name].map(smiles_to_description)
# Now generate embeddings tqdm.pandas(desc=f"Embedding {base_filename}") embeddings = df_full["Description"].progress_apply( lambda text: get_text_embeddings(text, scibert_tokenizer, scibert_model, device) ).tolist()
embeddings_array = np.array(embeddings)
output_file = os.path.join(root, f"{os.path.splitext(base_filename)[0]}_text_embedding.npy") np.save(output_file, embeddings_array)
print(f"Saved embeddings to {output_file}\n")
except Exception as e: print(f"Failed to process {filtered_path}: {e}\n")
# Example usagefolder_path = "/home/g3-bbm-project/main_folder/FineTune/finetune_data_multi/finetuning_datasets/classification" # Set your top-level folder hereprint(f"Starting to process folder: {folder_path}")process_folder(folder_path)print("Folder processing complete.")processing/dmgi_model.pyDeleted-103
processing/graph_embedding.pyDeleted-71
processing/npy_to_h5.pyDeleted-28
processing/pretrain_dmgi.pyDeleted-77
processing/selfies_embedding.pyDeleted-39
processing/smiles_to_selfies.pyDeleted-52
processing/text_embedding.pyDeleted-96