| # import requests | |
| # class DownloadEnamine: | |
| # """ | |
| # This class is set up to download Enamine REAL database on a remote machine. | |
| # Instatiation requires plain ``username`` and ``password``. | |
| # .. code-block::python | |
| # de = DownloadEnamine('[email protected]', 'Foo123') | |
| # de.download_all('REAL') | |
| # Note, this is copied off the route of the web page and not the Enamine Store API. | |
| # Plus the official documentation (emailed Word document) is for the old Store and | |
| # no longer applies anyway (plain text username and password in GET header "Authorization"). | |
| # The URLs pointing to the download pages were copied off manually. | |
| # """ | |
| # REAL=[ | |
| # '2024.07_Enamine_REAL_HAC_25_1B_CXSMILES.cxsmiles.bz2', | |
| # ] | |
| # LOGIN_URL = 'https://enamine.net/compound-collections/real-compounds/real-database' | |
| # def __init__(self, username, password): | |
| # self.sesh = requests.Session() | |
| # login_payload = { | |
| # 'username': username, | |
| # 'password': password, | |
| # 'Submit': 'Login', | |
| # 'remember': 'yes', | |
| # 'option': 'com_users', | |
| # 'task': 'user.login' | |
| # } | |
| # self.sesh.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}) | |
| # response = self.sesh.post(self.LOGIN_URL, data=login_payload) | |
| # response.raise_for_status() | |
| # print("Login appears successful.") | |
| # def download_all(self, catalogue='REAL'): | |
| # """ | |
| # The URLs of the databases files are in the class attribute of that same catalogue name (i.e. ``REAL``). | |
| # """ | |
| # for filename in getattr(self, catalogue): | |
| # self.download('REAL', filename) | |
| # def check(self, catalogue='REAL'): | |
| # for filename in getattr(self, catalogue): | |
| # with self.sesh.get(f'https://ftp.enamine.net/download/{catalogue}/{filename}', stream=True) as r: | |
| # r.raise_for_status() # requests.exceptions.HTTPError | |
| # for chunk in r.iter_content(chunk_size=8192): | |
| # break | |
| # def download(self, catalogue, filename): | |
| # """ | |
| # Downloads the ``filename`` of the given ``catalogue`` | |
| # """ | |
| # with self.sesh.get(f'https://ftp.enamine.net/download/{catalogue}/{filename}', stream=True) as r: | |
| # r.raise_for_status() | |
| # with open(filename, 'wb') as f: | |
| # for chunk in r.iter_content(chunk_size=8192): | |
| # f.write(chunk) | |
| # real_download = DownloadEnamine('[email protected]', 'Z!6CJd2BjQs!y4x') | |
| # real_download.download_all('REAL') | |
| import os | |
| import sys | |
| import random # <-- Import random module | |
| from rdkit import Chem | |
| # --- Configuration --- | |
| input_cxsmiles_file = "2024.07_Enamine_REAL_HAC_25_1B_CXSMILES.cxsmiles" # <-- CHANGE THIS to your input filename | |
| output_smiles_file = "smiles_sampled_20k.txt" # <-- CHANGE THIS to your desired output filename | |
| target_sample_size = 20000 # <-- How many molecules we want approximately | |
| # IMPORTANT: Provide a reasonable estimate of the total lines in the input file. | |
| # The filename '1B' suggests 1 billion. Accuracy affects how close the final count is to the target. | |
| estimated_total_lines = 1_000_000_000 # <-- ADJUST if your estimate differs | |
| # --- End Configuration --- | |
| # --- Script Start --- | |
| # Check if input file exists | |
| if not os.path.isfile(input_cxsmiles_file): | |
| print(f"ERROR: Input file not found: {input_cxsmiles_file}") | |
| sys.exit(1) | |
| # --- Calculate Sampling Probability --- | |
| if estimated_total_lines <= 0: | |
| print("ERROR: estimated_total_lines must be positive.") | |
| sys.exit(1) | |
| # Ensure probability is between 0 and 1 | |
| sampling_probability = min(1.0, target_sample_size / estimated_total_lines) | |
| print(f"Reading CXSMILES from: {input_cxsmiles_file}") | |
| print(f"Attempting to sample approximately {target_sample_size} lines.") | |
| print(f"Based on estimated total lines: {estimated_total_lines:,}") | |
| print(f"Calculated sampling probability per line: {sampling_probability:.8f}") | |
| print(f"Writing standard SMILES to: {output_smiles_file}") | |
| print("-" * 30) | |
| count_processed_lines = 0 # Lines read from input | |
| count_selected = 0 # Lines selected by random sampling | |
| count_success = 0 # Selected lines successfully converted | |
| count_error = 0 # Selected lines that failed conversion | |
| # Open input and output files safely | |
| try: | |
| with open(input_cxsmiles_file, 'r') as infile, open(output_smiles_file, 'w') as outfile: | |
| # Process each line in the input file | |
| for i, line in enumerate(infile): | |
| count_processed_lines += 1 | |
| cxsmiles_line = line.strip() # Remove leading/trailing whitespace | |
| if not cxsmiles_line: # Skip empty lines | |
| continue | |
| # --- Random Sampling Check --- | |
| if random.random() < sampling_probability: | |
| count_selected += 1 | |
| # --- Process Selected Line --- | |
| try: | |
| # RDKit's MolFromSmiles often ignores CXSMILES extensions | |
| # It reads the core structure. | |
| mol = Chem.MolFromSmiles(cxsmiles_line) | |
| if mol is not None: | |
| # Convert the RDKit molecule back to a standard, canonical SMILES | |
| standard_smiles = Chem.MolToSmiles(mol) | |
| outfile.write(standard_smiles + '\n') | |
| count_success += 1 | |
| else: | |
| # RDKit couldn't parse this selected line | |
| print(f"Warning: Could not parse selected line #{count_selected} (original line {i+1}). Input: '{cxsmiles_line}'") | |
| count_error += 1 | |
| except Exception as e: | |
| # Catch any other unexpected errors during RDKit processing | |
| print(f"Error processing selected line #{count_selected} (original line {i+1}): '{cxsmiles_line}'. Details: {e}") | |
| count_error += 1 | |
| # Optional: Print progress periodically for large files | |
| if (i + 1) % 1000000 == 0: # Print every 1 million lines processed | |
| print(f"Processed {i+1:,} lines. Selected: {count_selected}. Successful conversions: {count_success}.") | |
| except IOError as e: | |
| print(f"ERROR: Could not open or write file. Details: {e}") | |
| sys.exit(1) | |
| print("-" * 30) | |
| print(f"Processing finished.") | |
| print(f"Total lines read from input: {count_processed_lines:,}") | |
| print(f"Lines randomly selected for processing: {count_selected:,} (Target was approx. {target_sample_size:,})") | |
| print(f"Successfully converted: {count_success:,} lines.") | |
| print(f"Failed/Skipped (among selected): {count_error:,} lines.") | |
| print(f"Output written to: {output_smiles_file}") | |
| # Add a note about potential deviation from target | |
| if abs(count_selected - target_sample_size) > target_sample_size * 0.1: # If deviation > 10% | |
| print("\nNote: The actual number of selected lines differs significantly from the target.") | |
| print("This might be due to the 'estimated_total_lines' differing from the actual file size.") |