| 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 |
|
|
| |
| csv_file = "/Users/arunrajb/work/methanogenesis_work/sorted_molecules_MCDB.csv" |
| output_dir = "mol_output_from_csv" |
| os.makedirs(output_dir, exist_ok=True) |
|
|
| |
| def check_dependencies(): |
| if not which("obabel"): |
| raise EnvironmentError("β Open Babel (obabel) not found in PATH.") |
|
|
| |
| 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: |
| |
| mol = Chem.MolFromSmiles(smiles) |
| if mol is None: |
| raise ValueError("Invalid SMILES string.") |
| mol = Chem.AddHs(mol) |
|
|
| |
| 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) |
|
|
| |
| opt_status = AllChem.UFFOptimizeMolecule(mol, maxIters=20000) |
| if opt_status != 0: |
| print("β οΈ UFF optimization did not converge within max iterations.") |
|
|
| |
| Chem.MolToMolFile(mol, mol_path) |
|
|
| |
| diameter = calculate_diameter_rdkit(mol) |
|
|
| return mol, diameter |
|
|
| except Exception as e: |
| print(f"β οΈ RDKit processing failed: {e}") |
| return None, None |
|
|
| |
| 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 |
|
|
| |
| def process_csv(csv_file): |
| check_dependencies() |
|
|
| df = pd.read_csv(csv_file) |
| 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}") |
| print(f"π Diameter: Not available (Open Babel fallback)") |
| diameters.append(None) |
| else: |
| print(f"β
Saved: {mol_path}") |
| print(f"π Diameter: {diameter} Γ
") |
| diameters.append(diameter) |
|
|
| success_count += 1 |
|
|
| |
| 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}") |
|
|
| |
| if __name__ == "__main__": |
| process_csv(csv_file) |