Metadata-Version: 2.4
Name: moldom
Version: 0.1.0
Summary: Molecular Applicability Domain — check whether predictions are trustworthy using SHAP-based fingerprint similarity
Project-URL: Homepage, https://github.com/yourname/moldom
Project-URL: Repository, https://github.com/yourname/moldom
Project-URL: Issues, https://github.com/yourname/moldom/issues
License: MIT License
        
        Copyright (c) 2025
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: QSAR,RDKit,SHAP,applicability domain,cheminformatics,molecular similarity
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Chemistry
Requires-Python: >=3.8
Requires-Dist: numpy>=1.21
Requires-Dist: pandas>=1.3
Requires-Dist: rdkit>=2022.3
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: pytest-cov; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Description-Content-Type: text/markdown

# moldom — Molecular Applicability Domain

[![PyPI version](https://badge.fury.io/py/moldom.svg)](https://pypi.org/project/moldom/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

**Check whether molecular predictions are trustworthy** using SHAP-based fingerprint similarity.

When a QSAR/ML model makes a prediction on a new molecule, `moldom` answers:
> *"Is this molecule similar enough to the training set for the prediction to be reliable?"*

It uses two complementary fingerprint similarity metrics derived from SHAP feature importance:

| Metric | Reference fingerprint | Meaning |
|---|---|---|
| **Dice** | bits with non-zero SHAP | Structural coverage |
| **Tanimoto** | bits selected by `shap_direction` | Target-relevant feature match |

---

## Installation

```bash
pip install moldom
```

> **Requires RDKit.** If you don't have it:
> ```bash
> conda install -c conda-forge rdkit
> # or
> pip install rdkit
> ```

---

## Quick Start

```python
from moldom import check_ad

result = check_ad(
    query_smiles=["CCO", "c1ccccc1", "CC(=O)Oc1ccccc1C(=O)O"],
    shap="shap_features.csv",       # CSV with SHAP values, one per fingerprint bit
    train_smiles="train.csv",        # training set CSV (must have a 'SMILES' column)
)

print(result)
#                                SMILES      Dice  Tanimoto  in_AD  valid
# 0                                 CCO  0.412     0.318    True   True
# 1                           c1ccccc1  0.287     0.201   False   True
# 2  CC(=O)Oc1ccccc1C(=O)O             0.531     0.445    True   True

# Filter to in-domain molecules only
reliable = result[result.in_AD]
```

---

## API Reference

### `check_ad()`

```python
from moldom import check_ad

result = check_ad(
    query_smiles,           # str or list of SMILES to evaluate
    shap,                   # SHAP values: CSV path, array, DataFrame, or Series
    train_smiles,           # training SMILES: list or CSV path
    train_target=None,      # training target values (optional, for tanimoto filtering)

    # ── fingerprint ──────────────────────────────────────────────────────────
    radius=2,               # Morgan fingerprint radius

    # ── SHAP direction ───────────────────────────────────────────────────────
    shap_direction="positive",  # see below

    # ── threshold method ─────────────────────────────────────────────────────
    # Choose 'percentile', 'mean_std', or 'fixed' for each metric
    dice_method="percentile",
    tanimoto_method="mean_std",

    # percentile settings (used when method='percentile')
    dice_percentile=15.0,
    tanimoto_percentile=15.0,

    # mean-std settings (used when method='mean_std')
    dice_n_std=1.0,
    tanimoto_n_std=1.0,

    # fixed settings (used when method='fixed')
    dice_fixed=None,
    tanimoto_fixed=None,

    # ── target filtering for tanimoto baseline ───────────────────────────────
    target_col=None,             # column name if train_smiles is a CSV
    target_threshold=None,       # e.g. 0.2 — exclude low-activity molecules
    target_exclude_below=True,   # True = exclude molecules below threshold

    # ── output ───────────────────────────────────────────────────────────────
    return_scores=True,     # include Dice and Tanimoto columns in output
    n_jobs=1,               # parallel workers (>1 uses multiprocessing)
)
```

**Returns:** `pd.DataFrame` with columns `SMILES`, `Dice`, `Tanimoto`, `in_AD`, `valid`

The DataFrame also carries `.attrs["dice_threshold"]` and `.attrs["tanimoto_threshold"]`
so you can inspect the calibrated cutoffs.

---

## SHAP Direction

`shap_direction` controls which bits are used to build the Tanimoto reference fingerprint.
Choose based on what "good" means for your prediction target:

| Value | Bits used | When to use |
|---|---|---|
| `"positive"` *(default)* | SHAP > 0 | Target should be **high** (e.g. solubility, activity) |
| `"negative"` | SHAP < 0 | Target should be **low** (e.g. toxicity, side effects) |
| `"both"` | SHAP ≠ 0 | Direction doesn't matter / pure structural AD |

```python
# Predicting CO₂ solubility — higher is better
check_ad(..., shap_direction="positive")

# Predicting toxicity — lower is better
check_ad(..., shap_direction="negative")

# Just structural coverage, ignore direction
check_ad(..., shap_direction="both")
```

---

### `get_thresholds()`

Calibrate and inspect thresholds without screening any molecules:

```python
from moldom import get_thresholds

thresholds = get_thresholds(
    shap="shap_features.csv",
    train_smiles="train.csv",
    shap_direction="positive",
    dice_method="percentile",
    tanimoto_method="mean_std",
)
# {'dice_threshold': 0.341, 'tanimoto_threshold': 0.178}
```

---

## SHAP Input Formats

`check_ad` is flexible about how you provide SHAP values:

```python
# CSV file (column named 'Mean_SHAP_Value', 'shap', 'value', or last column)
check_ad(..., shap="shap_features.csv")

# numpy array
check_ad(..., shap=np.array([0.01, 0.0, -0.03, ...]))

# pandas Series
check_ad(..., shap=shap_series)

# single-column DataFrame
check_ad(..., shap=shap_df)
```

---

## Threshold Methods

| Method | Description | Key parameter |
|---|---|---|
| `"percentile"` | Lower percentile of training similarities | `dice_percentile` / `tanimoto_percentile` |
| `"mean_std"` | `mean - n * std` of training similarities | `dice_n_std` / `tanimoto_n_std` |
| `"fixed"` | User-specified constant | `dice_fixed` / `tanimoto_fixed` |

You can mix methods: e.g., `dice_method="percentile"` and `tanimoto_method="fixed"`.

---

## Replicating the Original CO₂ Script

```python
from moldom import check_ad

result = check_ad(
    query_smiles=il_df["IL_smile"].tolist(),
    shap="shap_feature_co2.csv",
    train_smiles="co2_train_clean.csv",
    train_target=train_df["co2"].tolist(),
    shap_direction="positive",       # high CO₂ solubility is desirable
    target_threshold=0.2,
    target_exclude_below=True,
    dice_method="percentile",
    dice_percentile=15.0,
    tanimoto_method="percentile",
    tanimoto_percentile=15.0,
    n_jobs=24,
)
```

---

## License

MIT
