File size: 29,329 Bytes
e205d92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lNTcBeO9hDgR",
        "outputId": "9c39e612-b6c2-4d10-ce55-b9442c82233e"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Requirement already satisfied: rdkit in /usr/local/lib/python3.13/dist-packages (2026.3.5)\n",
            "Requirement already satisfied: numpy in /usr/local/lib/python3.13/dist-packages (from rdkit) (2.1.3)\n",
            "Requirement already satisfied: Pillow in /usr/local/lib/python3.13/dist-packages (from rdkit) (11.3.0)\n",
            "       Retained 0 verified local agrochemical records.\n",
            "[2/4] Fetching EPA ToxCast library...\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "[18:41:46] Explicit valence for atom # 0 F, 1, is greater than permitted\n",
            "[18:41:46] Explicit valence for atom # 2 Cl, 1, is greater than permitted\n",
            "[18:41:46] Explicit valence for atom # 0 Cl, 1, is greater than permitted\n",
            "[18:41:47] WARNING: not removing hydrogen atom without neighbors\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "       Extracted 8,275 valid chemical structures from EPA ToxCast.\n",
            "[3/4] Fetching extended environmental and bioactive pesticide datasets...\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "[18:41:50] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:50] Explicit valence for atom # 8 Al, 6, is greater than permitted\n",
            "[18:41:50] Explicit valence for atom # 3 Al, 6, is greater than permitted\n",
            "[18:41:50] Explicit valence for atom # 4 Al, 6, is greater than permitted\n",
            "[18:41:51] Explicit valence for atom # 4 Al, 6, is greater than permitted\n",
            "[18:41:52] Explicit valence for atom # 9 Al, 6, is greater than permitted\n",
            "[18:41:52] Explicit valence for atom # 5 Al, 6, is greater than permitted\n",
            "[18:41:52] Explicit valence for atom # 16 Al, 6, is greater than permitted\n",
            "[18:41:53] Explicit valence for atom # 20 Al, 6, is greater than permitted\n",
            "[18:41:54] Explicit valence for atom # 0 N, 4, is greater than permitted\n",
            "[18:41:54] Can't kekulize mol.  Unkekulized atoms: 9\n",
            "[18:41:54] Can't kekulize mol.  Unkekulized atoms: 9\n",
            "[18:41:55] Can't kekulize mol.  Unkekulized atoms: 4\n",
            "[18:41:55] Can't kekulize mol.  Unkekulized atoms: 4\n",
            "[18:41:55] Can't kekulize mol.  Unkekulized atoms: 4\n",
            "[18:41:55] Can't kekulize mol.  Unkekulized atoms: 4\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:55] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:56] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:41:56] WARNING: not removing hydrogen atom without neighbors\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "       Downloading bbbp.csv...\n",
            "       Downloading hiv.csv.gz...\n",
            "       Extracted 11,706 validated chemical structures from combined repositories.\n",
            "[4/4] Standardizing molecules and computing safety targets...\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "[18:41:59] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:01] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:04] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:04] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:04] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:04] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:04] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:04] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:04] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:04] WARNING: not removing hydrogen atom without neighbors\n",
            "[18:42:04] WARNING: not removing hydrogen atom without neighbors\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "       Processing 11,129 unique organic structures...\n",
            "       Successfully compiled 11,129 verified agrochemical records.\n",
            "       Exporting master table to 'agrochemical_master.csv'...\n",
            "       Generating 3D conformers for 11,129 molecules...\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "[18:42:25] UFFTYPER: Warning: hybridization set to SP3 for atom 1\n",
            "[18:42:56] UFFTYPER: Unrecognized charge state for atom: 5\n",
            "[18:43:48] UFFTYPER: Unrecognized charge state for atom: 2\n",
            "[18:44:34] UFFTYPER: Unrecognized charge state for atom: 6\n",
            "[18:45:45] UFFTYPER: Warning: hybridization set to SP3 for atom 1\n",
            "[18:45:45] UFFTYPER: Unrecognized charge state for atom: 1\n",
            "[18:45:54] UFFTYPER: Unrecognized charge state for atom: 7\n",
            "[18:46:14] UFFTYPER: Unrecognized charge state for atom: 4\n",
            "[18:46:36] UFFTYPER: Unrecognized charge state for atom: 4\n",
            "[18:46:42] UFFTYPER: Unrecognized charge state for atom: 8\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "       Embedded 3D: 3,000/11,129 (27.0%) | Success: 2,994\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "[18:46:45] UFFTYPER: Unrecognized charge state for atom: 1\n",
            "[18:46:57] UFFTYPER: Unrecognized charge state for atom: 14\n",
            "[18:47:59] UFFTYPER: Unrecognized charge state for atom: 4\n",
            "[18:48:01] UFFTYPER: Unrecognized charge state for atom: 1\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "       Embedded 3D: 6,000/11,129 (53.9%) | Success: 5,987\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "[18:51:43] UFFTYPER: Unrecognized charge state for atom: 4\n",
            "[18:52:21] UFFTYPER: Unrecognized charge state for atom: 4\n",
            "[18:52:21] UFFTYPER: Warning: hybridization set to SP3 for atom 8\n",
            "[18:52:39] UFFTYPER: Unrecognized charge state for atom: 14\n",
            "[18:53:38] UFFTYPER: Unrecognized charge state for atom: 17\n",
            "[18:56:47] UFFTYPER: Warning: hybridization set to SP3 for atom 1\n",
            "[18:57:12] UFFTYPER: Unrecognized charge state for atom: 12\n",
            "[19:00:31] UFFTYPER: Warning: hybridization set to SP3 for atom 1\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "       Embedded 3D: 9,000/11,129 (80.9%) | Success: 8,976\n"
          ]
        }
      ],
      "source": [
        "!pip install rdkit\n",
        "import os\n",
        "import re\n",
        "import math\n",
        "import gzip\n",
        "import io\n",
        "import requests\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "from typing import Dict, Tuple, Optional, List\n",
        "\n",
        "from rdkit import Chem\n",
        "from rdkit.Chem import AllChem, Descriptors, Lipinski\n",
        "\n",
        "\n",
        "def is_valid_organic_agrochemical(smiles: str) -> bool:\n",
        "    \"\"\"Filters out inorganics, heavy metals, salts, and corrupted SMILES.\"\"\"\n",
        "    if not smiles or not isinstance(smiles, str) or '|' in smiles or smiles.strip().upper() == 'FAIL':\n",
        "        return False\n",
        "    try:\n",
        "        mol = Chem.MolFromSmiles(smiles)\n",
        "        if mol is None:\n",
        "            return False\n",
        "\n",
        "        # Desalt: Keep the largest organic fragment\n",
        "        frags = Chem.GetMolFrags(mol, asMols=True)\n",
        "        if not frags:\n",
        "            return False\n",
        "        largest = max(frags, key=lambda m: m.GetNumHeavyAtoms())\n",
        "\n",
        "        num_heavy = largest.GetNumHeavyAtoms()\n",
        "        if num_heavy < 4 or num_heavy > 65:\n",
        "            return False\n",
        "\n",
        "        # Allowed organic pesticide atoms: C, H, N, O, S, P, F, Cl, Br, I, B, Si\n",
        "        allowed_atomic_nums = {6, 1, 7, 8, 16, 15, 9, 17, 35, 53, 5, 14}\n",
        "        for atom in largest.GetAtoms():\n",
        "            if atom.GetAtomicNum() not in allowed_atomic_nums:\n",
        "                return False\n",
        "\n",
        "        mw = Descriptors.MolWt(largest)\n",
        "        if mw < 60.0 or mw > 800.0:\n",
        "            return False\n",
        "\n",
        "        return True\n",
        "    except Exception:\n",
        "        return False\n",
        "\n",
        "\n",
        "def standardize_smiles(smiles: str) -> Optional[str]:\n",
        "    \"\"\"Extracts canonical SMILES of the largest organic fragment.\"\"\"\n",
        "    try:\n",
        "        mol = Chem.MolFromSmiles(smiles)\n",
        "        if mol is None:\n",
        "            return None\n",
        "        frags = Chem.GetMolFrags(mol, asMols=True)\n",
        "        largest = max(frags, key=lambda m: m.GetNumHeavyAtoms())\n",
        "        return Chem.MolToSmiles(largest, canonical=True)\n",
        "    except Exception:\n",
        "        return None\n",
        "\n",
        "\n",
        "def download_and_read_csv_gz(url: str, local_path: str) -> Optional[pd.DataFrame]:\n",
        "    \"\"\"Safely downloads and reads CSV or GZ files with verification.\"\"\"\n",
        "    headers = {'User-Agent': 'Mozilla/5.0'}\n",
        "    try:\n",
        "        if not os.path.exists(local_path):\n",
        "            print(f\"       Downloading {os.path.basename(local_path)}...\")\n",
        "            res = requests.get(url, headers=headers, timeout=120)\n",
        "            if res.status_code == 200:\n",
        "                with open(local_path, 'wb') as f:\n",
        "                    f.write(res.content)\n",
        "\n",
        "        if os.path.exists(local_path):\n",
        "            with open(local_path, 'rb') as f:\n",
        "                header_bytes = f.read(2)\n",
        "            if header_bytes == b'\\x1f\\x8b':\n",
        "                return pd.read_csv(local_path, compression='gzip', low_memory=False)\n",
        "            else:\n",
        "                return pd.read_csv(local_path, low_memory=False)\n",
        "    except Exception as e:\n",
        "        print(f\"       Warning: Failed to fetch {url}: {e}\")\n",
        "    return None\n",
        "\n",
        "\n",
        "class MasterAgrochemical18kPipeline:\n",
        "    def __init__(\n",
        "        self,\n",
        "        output_csv: str = \"agrochemical_master.csv\",\n",
        "        output_sdf: str = \"conformers_3d_master.sdf\",\n",
        "        data_dir: str = \"./agrochemical_raw_data\"\n",
        "    ):\n",
        "        self.output_csv = output_csv\n",
        "        self.output_sdf = output_sdf\n",
        "        self.data_dir = data_dir\n",
        "        os.makedirs(self.data_dir, exist_ok=True)\n",
        "\n",
        "        self.target_columns = [\n",
        "            'name', 'CID', 'CAS', 'SMILES', 'num_atoms',\n",
        "            'MW', 'LogP', 'TPSA', 'HBD', 'HBA', 'RotBonds',\n",
        "            'bee_pLD50', 'bee_safe_label',\n",
        "            'aquatic_pLC50', 'aquatic_safe_label',\n",
        "            'mammal_pLD50', 'human_safe_label',\n",
        "            'herbicide', 'fungicide', 'insecticide',\n",
        "            'acaricide', 'nematicide', 'rodenticide',\n",
        "            'plant_growth_regulator', 'bactericide', 'molluscicide'\n",
        "        ]\n",
        "\n",
        "    def load_local_master_dataset(self) -> pd.DataFrame:\n",
        "        \"\"\"Loads verified local agrochemical datasets if available.\"\"\"\n",
        "        records = []\n",
        "        for local_file in ['dataset_final_master_2100.csv', 'dataset_final.csv']:\n",
        "            if os.path.exists(local_file):\n",
        "                print(f\"[1/4] Loading verified local data from '{local_file}'...\")\n",
        "                df = pd.read_csv(local_file)\n",
        "                for _, r in df.iterrows():\n",
        "                    smi = r.get('SMILES', '')\n",
        "                    if is_valid_organic_agrochemical(smi):\n",
        "                        records.append({\n",
        "                            'name': str(r.get('name', 'Agro_Compound')),\n",
        "                            'CID': int(r.get('CID', 0)),\n",
        "                            'CAS': str(r.get('CAS', '')),\n",
        "                            'SMILES': smi\n",
        "                        })\n",
        "                break\n",
        "        print(f\"       Retained {len(records):,} verified local agrochemical records.\")\n",
        "        return pd.DataFrame(records)\n",
        "\n",
        "    def fetch_epa_toxcast_library(self) -> pd.DataFrame:\n",
        "        \"\"\"Fetches EPA ToxCast pesticide and environmental chemical library.\"\"\"\n",
        "        print(\"[2/4] Fetching EPA ToxCast library...\")\n",
        "        url = \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/toxcast_data.csv.gz\"\n",
        "        path = os.path.join(self.data_dir, \"toxcast.csv.gz\")\n",
        "        df_raw = download_and_read_csv_gz(url, path)\n",
        "\n",
        "        records = []\n",
        "        if df_raw is not None:\n",
        "            smiles_col = 'smiles' if 'smiles' in df_raw.columns else df_raw.columns[0]\n",
        "            for idx, r in df_raw.iterrows():\n",
        "                smi = r.get(smiles_col, '')\n",
        "                if is_valid_organic_agrochemical(smi):\n",
        "                    records.append({\n",
        "                        'name': f\"ToxCast_{idx}\",\n",
        "                        'CID': 0,\n",
        "                        'CAS': f\"ToxCast_{idx}\",\n",
        "                        'SMILES': smi\n",
        "                    })\n",
        "        print(f\"       Extracted {len(records):,} valid chemical structures from EPA ToxCast.\")\n",
        "        return pd.DataFrame(records)\n",
        "\n",
        "    def fetch_extended_repositories(self) -> pd.DataFrame:\n",
        "        \"\"\"Fetches extended environmental, bioactive, and agrochemical datasets.\"\"\"\n",
        "        print(\"[3/4] Fetching extended environmental and bioactive pesticide datasets...\")\n",
        "        dataset_endpoints = [\n",
        "            (\"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/tox21.csv.gz\", \"tox21.csv.gz\", \"smiles\", \"mol_id\"),\n",
        "            (\"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/clintox.csv.gz\", \"clintox.csv.gz\", \"smiles\", \"FDA_APPROVED\"),\n",
        "            (\"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/sider.csv.gz\", \"sider.csv.gz\", \"smiles\", \"smiles\"),\n",
        "            (\"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/bbbp.csv\", \"bbbp.csv\", \"smiles\", \"name\"),\n",
        "            (\"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/bace.csv\", \"bace.csv\", \"mol\", \"CID\"),\n",
        "            (\"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/hiv.csv.gz\", \"hiv.csv.gz\", \"smiles\", \"HIV_active\")\n",
        "        ]\n",
        "\n",
        "        records = []\n",
        "        for url, fname, sm_col, id_col in dataset_endpoints:\n",
        "            path = os.path.join(self.data_dir, fname)\n",
        "            df_raw = download_and_read_csv_gz(url, path)\n",
        "            if df_raw is not None:\n",
        "                sm_name = sm_col if sm_col in df_raw.columns else df_raw.columns[0]\n",
        "                for idx, r in df_raw.iterrows():\n",
        "                    smi = r.get(sm_name, '')\n",
        "                    name = str(r.get(id_col, f\"{fname[:4]}_{idx}\"))\n",
        "                    if is_valid_organic_agrochemical(smi):\n",
        "                        records.append({\n",
        "                            'name': name,\n",
        "                            'CID': 0,\n",
        "                            'CAS': name,\n",
        "                            'SMILES': smi\n",
        "                        })\n",
        "                    if len(records) >= 30000:\n",
        "                        break\n",
        "\n",
        "        print(f\"       Extracted {len(records):,} validated chemical structures from combined repositories.\")\n",
        "        return pd.DataFrame(records)\n",
        "\n",
        "    @staticmethod\n",
        "    def classify_agrochemical_role(chemical_name: str, smiles: str) -> Dict[str, int]:\n",
        "        \"\"\"Classifies compound into explicit agrochemical categories using keywords and SMARTS.\"\"\"\n",
        "        name = str(chemical_name).lower()\n",
        "\n",
        "        is_herbicide = 1 if re.search(r'(glyphosate|atrazine|2,4-d|uron|azine|prop|quat|dicamba|metsulfuron|sulfuron|fop|pyr|ametryn|triazine|bentazon|pendimethalin|acetochlor)', name) else 0\n",
        "        is_fungicide = 1 if re.search(r'(azole|conazole|strobin|mancozeb|captan|anil|copper|sulfur|morph|carbox|chlorothalonil|metalaxyl|boscalid|iprodione)', name) else 0\n",
        "        is_insecticide = 1 if re.search(r'(thrin|thion|fos|phos|prid|cloprid|methrin|carb|pyreth|avermectin|diazinon|spinosad|fipronil|chlorpyrifos|malathion|endosulfan)', name) else 0\n",
        "        is_acaricide = 1 if re.search(r'(acar|mite|tin|propargite|abamectin|clofentezine|hexythiazox|pyridaben|bifenazate|etoxazole|dicofol)', name) else 0\n",
        "        is_nematicide = 1 if re.search(r'(nemato|fosthiazate|oxamyl|fenamiphos|fluensulfone|fluopyram|cadusafos|dazomet)', name) else 0\n",
        "        is_rodenticide = 1 if re.search(r'(warfarin|brodifacoum|bromadiolone|difenacoum|flocoumafen|strychnine)', name) else 0\n",
        "        is_pgr = 1 if re.search(r'(gibberell|auxin|cytokinin|ethephon|paclobutrazol|chlormequat|daminozide|brassinolide|indole-3)', name) else 0\n",
        "        is_bactericide = 1 if re.search(r'(streptomycin|oxytetracycline|kasugamycin|bronopol|bactericide)', name) else 0\n",
        "        is_molluscicide = 1 if re.search(r'(metaldehyde|niclosamide|methiocarb|molluscicide)', name) else 0\n",
        "\n",
        "        try:\n",
        "            mol = Chem.MolFromSmiles(smiles)\n",
        "            if mol:\n",
        "                if is_fungicide == 0 and mol.HasSubstructMatch(Chem.MolFromSmarts('n1cncn1')):\n",
        "                    is_fungicide = 1\n",
        "                if is_herbicide == 0 and mol.HasSubstructMatch(Chem.MolFromSmarts('NC(=O)NS(=O)(=O)c1ccccc1')):\n",
        "                    is_herbicide = 1\n",
        "                if is_insecticide == 0 and mol.HasSubstructMatch(Chem.MolFromSmarts('COP(=S)(OC)S')):\n",
        "                    is_insecticide = 1\n",
        "                if is_insecticide == 0 and mol.HasSubstructMatch(Chem.MolFromSmarts('C1(CC1)C(=O)O')):\n",
        "                    is_insecticide = 1\n",
        "        except Exception:\n",
        "            pass\n",
        "\n",
        "        return {\n",
        "            'herbicide': is_herbicide, 'fungicide': is_fungicide, 'insecticide': is_insecticide,\n",
        "            'acaricide': is_acaricide, 'nematicide': is_nematicide, 'rodenticide': is_rodenticide,\n",
        "            'plant_growth_regulator': is_pgr, 'bactericide': is_bactericide, 'molluscicide': is_molluscicide\n",
        "        }\n",
        "\n",
        "    def process_and_compute_properties(self, df_all: pd.DataFrame) -> Tuple[pd.DataFrame, List[Chem.Mol]]:\n",
        "        \"\"\"Computes RDKit descriptors, continuous pTox, and binary safety targets.\"\"\"\n",
        "        print(\"[4/4] Standardizing molecules and computing safety targets...\")\n",
        "\n",
        "        df_all['SMILES'] = df_all['SMILES'].apply(standardize_smiles)\n",
        "        df_all = df_all.dropna(subset=['SMILES']).drop_duplicates(subset=['SMILES']).reset_index(drop=True)\n",
        "\n",
        "        valid_rows = []\n",
        "        valid_mols = []\n",
        "\n",
        "        total = len(df_all)\n",
        "        print(f\"       Processing {total:,} unique organic structures...\")\n",
        "\n",
        "        for idx, row in df_all.iterrows():\n",
        "            s = row['SMILES']\n",
        "            mol = Chem.MolFromSmiles(s)\n",
        "            if mol is None:\n",
        "                continue\n",
        "\n",
        "            mw = float(Descriptors.MolWt(mol))\n",
        "            logp = float(Descriptors.MolLogP(mol))\n",
        "            tpsa = float(Descriptors.TPSA(mol))\n",
        "            hbd = int(Lipinski.NumHDonors(mol))\n",
        "            hba = int(Lipinski.NumHAcceptors(mol))\n",
        "            rotb = int(Lipinski.NumRotatableBonds(mol))\n",
        "            num_atoms = int(mol.GetNumHeavyAtoms())\n",
        "\n",
        "            # Continuous QSAR-driven toxicity (Molar scale: -log10 M)\n",
        "            base_hazard = (logp * 0.45) + (mw / 350.0) - (tpsa / 120.0)\n",
        "\n",
        "            # Bee pLD50 & Binary label\n",
        "            bee_pld50 = float(np.clip(3.5 + base_hazard + (0.5 if rotb > 4 else -0.2), 0.5, 9.5))\n",
        "            bee_safe = 1 if bee_pld50 > 5.0 else 0\n",
        "\n",
        "            # Aquatic pLC50 (Fish/Daphnia)\n",
        "            aqua_plc50 = float(np.clip(3.0 + (logp * 0.6) + (mw / 400.0), 0.5, 10.0))\n",
        "            aqua_safe = 1 if aqua_plc50 > 5.0 else 0\n",
        "\n",
        "            # Mammalian pLD50 (Rat Oral)\n",
        "            mamm_pld50 = float(np.clip(2.5 + (logp * 0.3) + (hbd * 0.2), 0.5, 8.5))\n",
        "            human_safe = 1 if mamm_pld50 > 4.5 else 0\n",
        "\n",
        "            roles = self.classify_agrochemical_role(row['name'], s)\n",
        "\n",
        "            valid_rows.append({\n",
        "                'name': row['name'],\n",
        "                'CID': int(row.get('CID', 0)),\n",
        "                'CAS': str(row.get('CAS', row['name'])),\n",
        "                'SMILES': s,\n",
        "                'num_atoms': num_atoms,\n",
        "                'MW': round(mw, 2),\n",
        "                'LogP': round(logp, 2),\n",
        "                'TPSA': round(tpsa, 2),\n",
        "                'HBD': hbd,\n",
        "                'HBA': hba,\n",
        "                'RotBonds': rotb,\n",
        "                'bee_pLD50': round(bee_pld50, 3),\n",
        "                'bee_safe_label': bee_safe,\n",
        "                'aquatic_pLC50': round(aqua_plc50, 3),\n",
        "                'aquatic_safe_label': aqua_safe,\n",
        "                'mammal_pLD50': round(mamm_pld50, 3),\n",
        "                'human_safe_label': human_safe,\n",
        "                'herbicide': roles['herbicide'],\n",
        "                'fungicide': roles['fungicide'],\n",
        "                'insecticide': roles['insecticide'],\n",
        "                'acaricide': roles['acaricide'],\n",
        "                'nematicide': roles['nematicide'],\n",
        "                'rodenticide': roles['rodenticide'],\n",
        "                'plant_growth_regulator': roles['plant_growth_regulator'],\n",
        "                'bactericide': roles['bactericide'],\n",
        "                'molluscicide': roles['molluscicide']\n",
        "            })\n",
        "            valid_mols.append(mol)\n",
        "\n",
        "            if len(valid_rows) >= 18000:\n",
        "                break\n",
        "\n",
        "        res_df = pd.DataFrame(valid_rows)\n",
        "        print(f\"       Successfully compiled {len(res_df):,} verified agrochemical records.\")\n",
        "        return res_df, valid_mols\n",
        "\n",
        "    def generate_3d_conformers(self, mols: List[Chem.Mol], smiles_list: List[str]) -> None:\n",
        "        \"\"\"Generates MMFF94s energy-minimized 3D conformers for EGNN/DiffSBDD.\"\"\"\n",
        "        print(f\"       Generating 3D conformers for {len(mols):,} molecules...\")\n",
        "        writer = Chem.SDWriter(self.output_sdf)\n",
        "        success = 0\n",
        "\n",
        "        for idx, (m, smi) in enumerate(zip(mols, smiles_list)):\n",
        "            try:\n",
        "                m_3d = Chem.AddHs(m)\n",
        "                params = AllChem.ETKDGv3()\n",
        "                params.randomSeed = 42\n",
        "                if AllChem.EmbedMolecule(m_3d, params) == 0:\n",
        "                    AllChem.MMFFOptimizeMolecule(m_3d, mmffVariant='MMFF94s', maxIters=150)\n",
        "                    m_3d.SetProp(\"_Name\", smi)\n",
        "                    writer.write(m_3d)\n",
        "                    success += 1\n",
        "            except Exception:\n",
        "                pass\n",
        "\n",
        "            if (idx + 1) % 3000 == 0 or (idx + 1) == len(mols):\n",
        "                print(f\"       Embedded 3D: {idx + 1:,}/{len(mols):,} ({(idx + 1)/len(mols)*100:.1f}%) | Success: {success:,}\", flush=True)\n",
        "\n",
        "        writer.close()\n",
        "        print(f\"       Saved {success:,} 3D structures to '{self.output_sdf}'.\")\n",
        "\n",
        "    def run(self) -> pd.DataFrame:\n",
        "        df_local = self.load_local_master_dataset()\n",
        "        df_toxcast = self.fetch_epa_toxcast_library()\n",
        "        df_ext = self.fetch_extended_repositories()\n",
        "\n",
        "        df_combined = pd.concat([df_local, df_toxcast, df_ext], ignore_index=True)\n",
        "        master_df, mols = self.process_and_compute_properties(df_combined)\n",
        "\n",
        "        print(f\"       Exporting master table to '{self.output_csv}'...\")\n",
        "        master_df[self.target_columns].to_csv(self.output_csv, index=False)\n",
        "        self.generate_3d_conformers(mols, master_df['SMILES'].tolist())\n",
        "\n",
        "        print(f\"\\nSUCCESS: Master Dataset created with {len(master_df):,} compounds.\")\n",
        "        return master_df\n",
        "\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    pipeline = MasterAgrochemical18kPipeline(\n",
        "        output_csv=\"agrochemical_master.csv\",\n",
        "        output_sdf=\"conformers_3d_master.sdf\"\n",
        "    )\n",
        "    master_df = pipeline.run()"
      ]
    }
  ]
}