import os import subprocess import pandas as pd import tempfile import numpy as np from rdkit import Chem from rdkit.Chem import AllChem from shutil import which # === Settings === csv_file = "/work/ratul1/arunraj/conda_work/methano_work_size/sorted_molecules_BMDB_copy.csv" # input CSV output_dir = "mol_output_from_csv_BMDB" os.makedirs(output_dir, exist_ok=True) # === Check for Open Babel === def check_dependencies(): if not which("obabel"): raise EnvironmentError("❌ Open Babel (obabel) not found in PATH.") # === Diameter Calculation === def calculate_diameter_rdkit(mol): """Compute molecular diameter from 3D coordinates""" try: conf = mol.GetConformer() coords = np.array([conf.GetAtomPosition(i) for i in range(mol.GetNumAtoms())]) dist = np.linalg.norm(coords[:, None, :] - coords[None, :, :], axis=-1) return round(np.max(dist), 2) except: return None def smiles_to_mol_rdkit(smiles, mol_path): try: # Convert SMILES to RDKit Mol mol = Chem.MolFromSmiles(smiles) if mol is None: raise ValueError("Invalid SMILES string.") mol = Chem.AddHs(mol) # 3D Conformer Generation params = AllChem.ETKDGv3() params.randomSeed = 42 success = AllChem.EmbedMolecule(mol, params) if success != 0: print("⚠️ ETKDG embedding failed, retrying with random coordinates...") AllChem.EmbedMolecule(mol, useRandomCoords=True) # UFF Optimization with increased iterations opt_status = AllChem.UFFOptimizeMolecule(mol, maxIters=20000) if opt_status != 0: print("⚠️ UFF optimization did not converge within max iterations.") # Save to .mol file Chem.MolToMolFile(mol, mol_path) # Calculate diameter diameter = calculate_diameter_rdkit(mol) return mol, diameter except Exception as e: print(f"⚠️ RDKit processing failed: {e}") return None, None # === Fallback to Open Babel (.mol) === def smiles_to_mol_obabel(smiles, mol_path): try: with tempfile.NamedTemporaryFile(mode='w', suffix='.smi', delete=False) as tmp: tmp.write(smiles) tmp_path = tmp.name subprocess.run(["obabel", "-ismi", tmp_path, "-O", mol_path, "--gen3d"], check=True) os.remove(tmp_path) return True except Exception as e: print(f"⚠️ Open Babel fallback failed: {e}") return False # === Main Processing === def process_csv(csv_file): check_dependencies() df = pd.read_csv(csv_file) # With header diameters = [] success_count, fail_count = 0, 0 failures = [] for idx, row in df.iterrows(): name = str(row["Molecule Name"]).strip() smiles = str(row["Smiles"]).strip() if not smiles or pd.isna(smiles) or smiles.lower() == "nan": print(f"[{idx+1}] ⚠️ Skipping {name} due to invalid SMILES") diameters.append(None) continue tag = name.replace(" ", "_").replace("/", "_").replace(":", "_") mol_path = os.path.join(output_dir, f"{tag}.mol") if os.path.exists(mol_path): print(f"[{idx+1}] ⏩ Skipping {name} (already exists)") mol = Chem.MolFromMolFile(mol_path, removeHs=False) if mol: diameter = calculate_diameter_rdkit(mol) diameters.append(diameter) print(f"📏 Diameter (existing): {diameter} Å") else: diameters.append(None) continue print(f"[{idx+1}] Processing: {name}") mol, diameter = smiles_to_mol_rdkit(smiles, mol_path) if mol is None: print("⏪ Falling back to Open Babel...") if not smiles_to_mol_obabel(smiles, mol_path): print(f"❌ Failed: {name}") failures.append((name, "3D generation failed")) diameters.append(None) fail_count += 1 continue print(f"✅ Saved: {mol_path}") # NEW: Attempt diameter calculation from Open Babel mol file using RDKit mol_ob = Chem.MolFromMolFile(mol_path, removeHs=False) if mol_ob: diameter = calculate_diameter_rdkit(mol_ob) diameters.append(diameter) print(f"📏 Diameter (Open Babel): {diameter} Å") else: diameters.append(None) print(f"❌ RDKit could not parse Open Babel .mol file") else: print(f"✅ Saved: {mol_path}") print(f"📏 Diameter: {diameter} Å") diameters.append(diameter) success_count += 1 # Add Diameter column and overwrite CSV df["Diameter"] = diameters df.to_csv(csv_file, index=False) print(f"\n✅ Updated CSV saved with Diameter column: {csv_file}") print(f"🎉 Done. {success_count} succeeded, {fail_count} failed.") if failures: fail_log = os.path.join(output_dir, "failed_log.txt") with open(fail_log, "w") as f: for name, reason in failures: f.write(f"{name}\t{reason}\n") print(f"📄 Failures logged in: {fail_log}") # === Run === if __name__ == "__main__": process_csv(csv_file)