#!/bin/python import pandas as pd import numpy as np from rdkit import Chem from rdkit.Chem import Descriptors # this function is to fill rows in which the protein structure is the same, but there are multiple ligands (appearing as multiple rows) bound to the protein def fill_nans_iteratively(df): """ Iteratively fill NaN values in rows that have NaNs in all columns except 'Ligand ID', 'Ligand Name', 'Ligand SMILES', and 'Protein' Parameters: df: pandas DataFrame Returns: DataFrame with filled values """ # make a copy to avoid modifying the original df_filled = df.copy() # define columns to exclude from the NaN check exclude_cols = ['Ligand ID', 'Ligand Name', 'Ligand SMILES', 'Protein'] # get all other columns other_cols = [col for col in df_filled.columns if col not in exclude_cols] # iterate through rows starting from index 1 (second row) for i in range(1, len(df_filled)): # check if current row has NaN in all other columns current_row_other_cols = df_filled.loc[df_filled.index[i], other_cols] if current_row_other_cols.isna().all(): # get the previous row's values for the other columns prev_row_values = df_filled.loc[df_filled.index[i-1], other_cols] # fill NaN values in current row with previous row's values df_filled.loc[df_filled.index[i], other_cols] = prev_row_values return df_filled def calculate_mol_weight(smiles): """Helper function to calculate molecular weight from SMILES""" if pd.isna(smiles) or not isinstance(smiles, str): return np.nan try: mol = Chem.MolFromSmiles(smiles) if mol is not None: return Descriptors.MolWt(mol) else: return np.nan except: return np.nan # this function filters by molecular weight to remove rows where the ligands are crystallization agents, ions, cofactors def filter_by_molecular_weight(df, min_weight=150, max_weight=1000): """ Filter df by ligands within molecular weight range """ df['Molecular Weight'] = df['Ligand SMILES'].apply(calculate_mol_weight) successful = df['Molecular Weight'].notna().sum() total = len(df) if successful == 0: print("WARNING: No molecules were successfully processed!") # show some examples of the SMILES strings for debugging print("Sample SMILES strings:") print(df['Ligand Smiles'].head(10).tolist()) return pd.DataFrame() mw_filtered_df = df[ (df['Molecular Weight'].notna()) & (df['Molecular Weight'] >= min_weight) & (df['Molecular Weight'] <= max_weight) ] # finally, remove any where pdb id is not present mw_filtered_df = mw_filtered_df[(mw_filtered_df['Entry ID'].notna())] return mw_filtered_df