ADORE: Acute Aquatic Toxicity Benchmark for Machine Learning (Fish, Crustaceans, Algae): sample notebook

A worked notebook for ADORE: Acute Aquatic Toxicity Benchmark for Machine Learning (Fish, Crustaceans, Algae), with 6 code cells and the output each one printed. On Scigantic it opens in a hosted JupyterLab with the dataset already mounted, so nothing is downloaded first.

Provider
Christoph Schür, Lilian Gasser, Fernando Perez-Cruz, Kristin Schirmer, Marco Baity-Jesi (Eawag, Swiss Data Science Center)
License
CC-BY-4.0
Size
68 objects, 3.0 GB
Stored at
Amazon S3, s3://scigantic-adore (us-east-1)
Access
Free and public. No account with the data provider is needed.

The notebook

ADORE: acute aquatic toxicity, and why the split you pick decides your score

ADORE is a benchmark for machine learning in ecotoxicology from Eawag and the Swiss Data Science Center. It holds 33,448 acute toxicity results (LC50 and EC50, 24 to 96 hours) for 2,408 chemicals on 203 species of fish, crustaceans and algae, drawn from the US EPA ECOTOX Knowledgebase and joined to chemical features (fingerprints, mol2vec, 719 Mordred descriptors) and species features (taxonomy, phylogenetic distance, life history).

The dataset's real contribution is not the rows, it is the eleven fixed challenges, each with its own train/test and 5-fold assignments. This notebook does three things:

The gap between (2) and (3) is the whole reason the benchmark exists.

Mirrored from doi:10.25678/0008C9 under CC BY 4.0.

import os, numpy as np, pandas as pd

MOUNT = os.environ.get("SCIGANTIC_MOUNT_PATH", "/mnt/archive")
P = f"{MOUNT}/parquet/processed"

# Read the parquet copies, not the csv: same rows and column names, 281 MB against 2.74 GB.
# t-F2F = train on fish, test on fish. The largest of the eleven challenges.
cols = ["test_cas", "chem_name", "chem_rdkit_can_smiles", "tax_gs", "result_effect",
        "result_endpoint", "result_obs_duration_mean", "result_conc1_mean",
        "result_conc1_mean_mol_log", "split_occurrence", "split_totallyrandom"]
df = pd.read_parquet(f"{P}/t-F2F_mortality.parquet", columns=cols)

print(f"{len(df):,} rows · {df.test_cas.nunique():,} chemicals · {df.tax_gs.nunique()} fish species")
df.head(3)

The eleven challenges

Each file in processed/ ending in _mortality.csv is one task. a-* train and test on different taxonomic groups, t-* stay inside one group, s-* are a single species.

challenges = pd.DataFrame([
    ("a-CA2F-same", "crustaceans + algae", "fish (same chemicals)", 28912),
    ("a-CA2F-diff", "crustaceans + algae", "fish (unseen chemicals)", 10910),
    ("a-FCA2FCA",   "everything",          "everything",             33448),
    ("t-F2F",       "fish",                "fish",                   26114),
    ("t-C2C",       "crustaceans",         "crustaceans",             6630),
    ("t-A2A",       "algae",               "algae",                    704),
    ("s-F2F-1",     "rainbow trout",       "rainbow trout",           4641),
    ("s-F2F-2",     "fathead minnow",      "fathead minnow",          4219),
    ("s-F2F-3",     "bluegill",            "bluegill",                3945),
    ("s-C2C",       "Daphnia magna",       "Daphnia magna",           5196),
    ("s-A2A",       "Chlorella vulgaris",  "Chlorella vulgaris",       163),
], columns=["challenge", "train on", "test on", "rows"])
challenges

The target, and what it actually measures

result_conc1_mean is the effect concentration in mg/L; the modelling target is usually its log10 in mol/L. Note that "mortality" in the filename is only true for fish: the algae rows are growth and population EC50s, and half the crustacean rows are immobilisation.

print(df.result_conc1_mean_mol_log.describe()[["count", "mean", "std", "min", "max"]].round(2).to_string())

# Across the whole dataset the assay mix differs by taxonomic group:
allrows = pd.read_parquet(f"{P}/a-FCA2FCA_mortality.parquet",
                          columns=["tax_group", "result_effect", "result_endpoint"])
print()
print(pd.crosstab(allrows.tax_group, [allrows.result_effect, allrows.result_endpoint]).to_string())

The noise floor

The same chemical on the same species under the same conditions was often tested many times, and the answers disagree. Any RMSE below that disagreement is fitting the repeats, not the chemistry.

rep = (df.groupby(["test_cas", "tax_gs", "result_effect", "result_obs_duration_mean"])
         .result_conc1_mean_mol_log.agg(["size", "std", lambda s: s.max() - s.min()])
         .rename(columns={"<lambda_0>": "spread"}))
multi = rep[rep["size"] > 1]
print(f"{len(rep):,} experimental settings, {len(multi):,} of them repeated "
      f"({multi['size'].sum():,} of {len(df):,} rows)")
print(f"median spread within a repeated setting: {multi.spread.median():.2f} log units")
print(f"90th percentile: {multi.spread.quantile(0.9):.2f}   max: {multi.spread.max():.2f}")
print(f"most repeated: {multi['size'].max()} runs of one setting")

Fit a baseline on the recommended split

split_occurrence is the authors' default: chemicals are ranked by how often they were tested and every sixth one goes to the test set, giving an 83:17 split in which no chemical appears on both sides. Values "0" to "4" are the cross-validation folds inside training.

from sklearn.ensemble import RandomForestRegressor

def fingerprint_matrix(col):
    """The fingerprints are stored as strings of '0'/'1' characters."""
    return np.frombuffer(col.str.cat().encode(), "u1").reshape(len(col), -1) - 48

feat_cols = ["chem_MACCS_fp", "test_cas", "result_obs_duration_mean",
             "result_conc1_mean_mol_log", "split_occurrence", "split_totallyrandom",
             "chem_rdkit_can_smiles"]
fp = pd.read_parquet(f"{P}/t-F2F_mortality.parquet", columns=feat_cols)

def evaluate(split):
    tr, te = fp[fp[split] != "test"], fp[fp[split] == "test"]
    Xtr = np.hstack([fingerprint_matrix(tr.chem_MACCS_fp),
                     tr[["result_obs_duration_mean"]].to_numpy()])
    Xte = np.hstack([fingerprint_matrix(te.chem_MACCS_fp),
                     te[["result_obs_duration_mean"]].to_numpy()])
    ytr, yte = tr.result_conc1_mean_mol_log, te.result_conc1_mean_mol_log
    rf = RandomForestRegressor(n_estimators=120, min_samples_leaf=2,
                               n_jobs=-1, random_state=0).fit(Xtr, ytr)
    rmse = lambda e: float(np.sqrt(np.mean(np.asarray(e) ** 2)))
    shared = te.test_cas.isin(set(tr.test_cas)).mean()
    return {"split": split, "n_test": len(te),
            "test rows on a chemical seen in training": f"{shared:.1%}",
            "RMSE, predict the training mean": round(rmse(yte - ytr.mean()), 3),
            "RMSE, random forest": round(rmse(yte - rf.predict(Xte)), 3)}

results = pd.DataFrame([evaluate("split_occurrence"), evaluate("split_totallyrandom")])
results.set_index("split").T

Read that table carefully

split_totallyrandom splits rows, not chemicals. Because the same chemical was tested many times, 97% of its test rows sit on a chemical the model already saw in training, and the score improves dramatically. Nothing about the model got better: it is reciting the training set.

This is why a result is only comparable to the paper, or to anyone else's, when it names the challenge file and the split column. The paper's own advice is to never use the totally random split. split_random, split_occurrence and the scaffold splits are all chemical-disjoint.

One caveat even on the clean splits: they are disjoint by CAS number, while chem_rdkit_can_smiles carries no stereochemistry, so isomers registered under different CAS numbers collapse to one structure.

tr = fp[fp.split_occurrence != "test"]
te = fp[fp.split_occurrence == "test"]
assert not (set(te.test_cas) & set(tr.test_cas)), "split_occurrence is CAS-disjoint"

bleed = te[te.chem_rdkit_can_smiles.isin(set(tr.chem_rdkit_can_smiles))]
print(f"{len(bleed)} of {len(te)} test rows ({len(bleed)/len(te):.1%}) share a flat SMILES "
      f"with training, across {bleed.chem_rdkit_can_smiles.nunique()} structures")

smi = bleed.chem_rdkit_can_smiles.iloc[0]
full = pd.read_parquet(f"{P}/t-F2F_mortality.parquet",
                       columns=["test_cas", "chem_name", "chem_rdkit_can_smiles"])
print("\nSame structure, different CAS numbers:")
print(full[full.chem_rdkit_can_smiles == smi][["test_cas", "chem_name"]].drop_duplicates().to_string(index=False))

Where to go next

a-CA2F-diff asks you to train on crustaceans and algae and predict fish, with no shared chemicals. The two a-CA2F-* files have 1,098 columns rather than 1,106: they carry no scaffold splits.

(chem_mordred_*), 300 mol2vec dimensions and four fingerprints. Species features (tax_eco_*, tax_lh_*, tax_ps_*) are null for all 704 algae rows, and tax_pdm_available, chem_ws_binary and chem_mol2vec_allowed are constant True, so drop them.

only by letter case (chem_mordred_naRing vs chem_mordred_nARing). DuckDB and most SQL engines fold those names; pandas and pyarrow keep them.

its key as InChIKey=..., so strip the prefix before joining on chem_inchikey. taxonomy/FCA_pdm_species.parquet is the phylogenetic distance matrix for all 203 species.

Cite Schür et al., *Scientific Data* 10, 718 (2023) and the dataset, doi:10.25678/0008C9.

Run it

Open this notebook to run it, see the dataset page for the full description, or browse the full catalog.