import torch import csv import pickle import os import numpy as np from rdkit import Chem import pandas as pd from torch_geometric.data import Data from torch_geometric.nn import GCNConv import torch.nn.functional as F from transformers import AutoTokenizer, AutoModel from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler def load_csv_data(filename): mylist = [] with open(filename) as data: csv_data = csv.reader(data, delimiter=',') next(csv_data) # Skip header row for row in csv_data: if any(row): # Check if any element in the row is non-empty mylist.append(row) return mylist # Define the color (255, 102, 153) in RGB, and add transparency color1 = (255/255, 102/255, 153/255) # Normalize RGB values to [0, 1] custom_cmap_pink = LinearSegmentedColormap.from_list("transparent_to_color",[(0, (*color1, 0)), (1, (*color1, 1))], N=256) color2 = (102/255, 153/255, 255/255) # Normalize RGB values to [0, 1] custom_cmap_blue = LinearSegmentedColormap.from_list("transparent_to_color",[(0, (*color2, 0)), (1, (*color2, 1))], N=256) color3 = (250/255, 147/255, 62/255) # Normalize RGB values to [0, 1] custom_cmap_orange = LinearSegmentedColormap.from_list("transparent_to_color",[(0, (*color3, 0)), (1, (*color3, 1))], N=256) color4 = (20/255, 165/255, 248/255) # Normalize RGB values to [0, 1] custom_cmap_button_blue = LinearSegmentedColormap.from_list("transparent_to_color",[(0, (*color4, 0)), (1, (*color4, 1))], N=256) color5 = (8/255, 253/255, 237/255) # Normalize RGB values to [0, 1] custom_cmap_turquoise_blue = LinearSegmentedColormap.from_list("transparent_to_color",[(0, (*color5, 0)), (1, (*color5, 1))], N=256) color6 = (224/255, 36/255, 159/255) # Normalize RGB values to [0, 1] custom_cmap_barbie_pink = LinearSegmentedColormap.from_list("transparent_to_color",[(0, (*color6, 0)), (1, (*color6, 1))], N=256) color7 = (80/255, 200/255, 120/255) # Normalize RGB values to [0, 1] custom_cmap_emerald_green = LinearSegmentedColormap.from_list("transparent_to_color",[(0, (*color7, 0)), (1, (*color7, 1))], N=256) def check_dir(folder_path): if not os.path.exists(folder_path): os.makedirs(folder_path) print(f"Folder '{folder_path}' created.") else: print(f"Folder '{folder_path}' already exists.") def extract_list_from_pickle(file_path): with open(file_path, 'rb') as file: data_list = pickle.load(file) return data_list def extract_data_from_sdf(file_path): with open(file_path, 'r') as file: lines = file.readlines() mapped_data = [] canonical_smiles_set = set() # Set to track canonical Kekulé SMILES and avoid duplicates current_smiles = None current_generic_name = None index = 0 # Initialize a new index for the extracted data for i, line in enumerate(lines): if line.strip() == '> ': current_smiles = lines[i + 1].strip() elif line.strip() == '> ': current_generic_name = lines[i + 1].strip() elif line.strip() == '$$$$': if current_smiles and current_generic_name: m = Chem.MolFromSmiles(current_smiles) if m is not None: # Get the canonical SMILES with Kekulé form canonical_kekule_smiles = Chem.MolToSmiles(m, canonical=True, kekuleSmiles=True) # Check if the canonical Kekulé SMILES is already in the set if canonical_kekule_smiles not in canonical_smiles_set: canonical_smiles_set.add(canonical_kekule_smiles) # Add to the set if it's new rdkit_smiles = Chem.MolToSmiles(m, canonical=True, kekuleSmiles=True) # Append the index along with the other data mapped_data.append([index, current_smiles, rdkit_smiles, current_generic_name]) print([index, current_smiles, rdkit_smiles, current_generic_name]) index += 1 # Increment the index for each valid data entry # Reset for the next entry current_smiles = None current_generic_name = None return mapped_data def extract_smiles_from_txt(file_path): smiles_list = [] try: with open(file_path, 'r') as file: for line in file: smiles = line.strip() # Remove any leading/trailing whitespace if smiles: # Check if the line is not empty smiles_list.append(smiles) else: print(f"Empty line found in {file_path}") except FileNotFoundError: print(f"File not found: {file_path}") except IOError: print(f"Error reading file: {file_path}") return smiles_list def one_hot_encoding(value, choices): encoding = [0] * len(choices) encoding[choices.index(value)] = 1 return encoding def smiles_to_graph(smiles): mol = Chem.MolFromSmiles(smiles) if mol is None: return None Chem.Kekulize(mol) adj = Chem.GetAdjacencyMatrix(mol) atom_features = [] for atom in mol.GetAtoms(): atom_features.append(one_hot_encoding(atom.GetAtomicNum(), [1, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 42, 46, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 60, 65, 73, 74, 75, 79, 80, 81, 82, 83, 92])) x = torch.tensor(atom_features, dtype=torch.float) edge_index = torch.tensor(np.where(adj), dtype=torch.long) return Data(x=x, edge_index=edge_index) class GNN(torch.nn.Module): def __init__(self): super(GNN, self).__init__() self.conv1 = GCNConv(58, 64) self.conv2 = GCNConv(64, 128) # as atoms present in the mcdb is 51, updated the model from 48 to 64. # checks the claude_model2, where the model takes in leng of atoms list. def forward(self, data): x, edge_index = data.x, data.edge_index x = self.conv1(x, edge_index) x = F.relu(x) x = self.conv2(x, edge_index) return x def atom_molecule_agg(gnn_output): return torch.mean(gnn_output, dim=0) def smiles_ChemBERTa_embedding(smiles_list, model_name='seyonec/PubChem10M_SMILES_BPE_450k'): # Load the tokenizer and model tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModel.from_pretrained(model_name) # Tokenize the SMILES strings inputs = tokenizer(smiles_list, return_tensors='pt', padding=True, truncation=False) # Get the model outputs with torch.no_grad(): outputs = model(**inputs) last_hidden_state = outputs.last_hidden_state # Get the attention mask to identify the padding tokens attention_mask = inputs['attention_mask'] # Calculate the mean embedding for each sequence, ignoring the padding tokens mean_embeddings = [] for i in range(last_hidden_state.size(0)): mask = attention_mask[i].unsqueeze(-1).expand_as(last_hidden_state[i]) masked_embedding = last_hidden_state[i] * mask sum_embedding = masked_embedding.sum(dim=0) count_non_pad_tokens = attention_mask[i].sum() mean_embedding = sum_embedding / count_non_pad_tokens mean_embeddings.append(mean_embedding) mean_embeddings = torch.stack(mean_embeddings) # Calculate the final mean embedding across all sequences final_mean_embedding = mean_embeddings.mean(dim=0) return final_mean_embedding def process_data(data_list): try: # Initialize lists generic_name, smiles, confidence, permeability_class, chemberta_embeddings, permeability_values = [], [], [], [], [], [] # Process each item in the data list for i, item in enumerate(data_list): if len(item) < 6: raise IndexError(f"Item at index {i} does not have enough elements: {item}") #index.append(item[0]) generic_name.append(item[0]) smiles.append(item[1]) confidence.append(item[2]) permeability_class.append(item[3]) chemberta_embeddings.append(item[4]) permeability_values.append(item[5]) # Stack the embeddings into a tensor stacked_tensor = torch.stack(chemberta_embeddings, dim=0) # Return processed data return generic_name, smiles, confidence, permeability_class, stacked_tensor, permeability_values except IndexError as e: print(f"IndexError: {e}. Check the structure and content of the data list.") return None, None, None except Exception as e: print(f"An unexpected error occurred: {e}") return None, None, None def take_unique_tensors(list_of_tensors): unique_tensors = [] for i, tensor in enumerate(list_of_tensors): # Use enumerate to get index if not any(torch.equal(tensor, unique_tensor) for unique_tensor in unique_tensors): unique_tensors.append(tensor) else: print(f"Duplicate found at index: {i}") # Print the number of unique tensors print(f"Number of unique tensors: {len(unique_tensors)}") return unique_tensors def process_data_old(data_list): try: # Initialize lists original_smiles, rdkit_smiles, chemberta_embeddings = [], [], [] # Process each item in the data list for i, item in enumerate(data_list): if len(item) < 3: raise IndexError(f"Item at index {i} does not have enough elements: {item}") original_smiles.append(item[1]) rdkit_smiles.append(item[2]) chemberta_embeddings.append(item[3]) # Stack the embeddings into a tensor stacked_tensor = torch.stack(chemberta_embeddings, dim=0) # Return processed data return original_smiles, rdkit_smiles, stacked_tensor except IndexError as e: print(f"IndexError: {e}. Check the structure and content of the data list.") return None, None, None except Exception as e: print(f"An unexpected error occurred: {e}") return None, None, None def process_data1(data_list): try: # Initialize lists index, generic_name, smiles, confidence, permeability_class, chemberta_embeddings, permeability_values = [], [], [], [], [], [], [] # Process each item in the data list for i, item in enumerate(data_list): if len(item) < 6: raise IndexError(f"Item at index {i} does not have enough elements: {item}") index.append(item[0]) generic_name.append(item[1]) smiles.append(item[2]) confidence.append(item[3]) permeability_class.append(item[4]) chemberta_embeddings.append(item[5]) permeability_values.append(item[6]) # Stack the embeddings into a tensor stacked_tensor = torch.stack(chemberta_embeddings, dim=0) # Return processed data return index, generic_name, smiles, confidence, permeability_class, stacked_tensor, permeability_values except IndexError as e: print(f"IndexError: {e}. Check the structure and content of the data list.") return None, None, None except Exception as e: print(f"An unexpected error occurred: {e}") return None, None, None def sort_by_distance_with_names_and_permeability(ref_points, data_points, sorted_names, normalized_permeability): ref_points = np.expand_dims(ref_points, axis=1) distances = np.linalg.norm(data_points - ref_points, axis=2) min_distances = np.min(distances, axis=0) sorted_indices = np.argsort(min_distances) # Sort data points, distances, and names using the sorted indices sorted_points = data_points[sorted_indices] sorted_distances = min_distances[sorted_indices] new_sorted_names = [sorted_names[i] for i in sorted_indices] # Apply sorting to names sorted_permeability = [normalized_permeability[i] for i in sorted_indices] # Apply sorting to permeability return sorted_points, sorted_distances, new_sorted_names, sorted_permeability def calculate_distances(ref_points, data_points, cutoff): ref_points = np.expand_dims(ref_points, axis=1) distances = np.linalg.norm(data_points - ref_points, axis=2) mask = distances < cutoff return data_points[np.any(mask, axis=0)] def sort_by_distance_with_names_and_permeability(ref_points, data_points, all_sorted_names, normalized_permeability, all_sorted_smiles): ref_points = np.expand_dims(ref_points, axis=1) distances = np.linalg.norm(data_points - ref_points, axis=2) min_distances = np.min(distances, axis=0) sorted_indices = np.argsort(min_distances) # Sort data points, distances, and names using the sorted indices sorted_points = data_points[sorted_indices] sorted_distances = min_distances[sorted_indices] new_sorted_names = [all_sorted_names[i] for i in sorted_indices] # Apply sorting to names sorted_permeability = [normalized_permeability[i] for i in sorted_indices] # Apply sorting to permeability sorted_smiles_string = [all_sorted_smiles[i] for i in sorted_indices] return sorted_points, sorted_distances, new_sorted_names, sorted_permeability, sorted_smiles_string def calculate_distances(ref_points, data_points, cutoff): ref_points = np.expand_dims(ref_points, axis=1) distances = np.linalg.norm(data_points - ref_points, axis=2) mask = distances < cutoff return data_points[np.any(mask, axis=0)]