> ## Documentation Index
> Fetch the complete documentation index at: https://khaos-ml.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Chemistry

> Molecules: virtual screening, similarity search, lead profiling.

## Screen a compound library

**Problem:** keep only compounds with drug-like lipophilicity, good solubility and
low predicted toxicity. **Uses:** Khaos, RDKit and pandas.

```python theme={null}
import khaos
import pandas as pd
from rdkit import Chem

logp = khaos.load("chem_logp")
solubility = khaos.load("chem_solubility")
toxicity = khaos.load("chem_toxicity")

rows = []
for smi in library_smiles:
    mol = Chem.MolFromSmiles(smi)
    if mol is None:
        continue
    canon = Chem.MolToSmiles(mol)
    rows.append({
        "smiles": canon,
        "logp": logp(canon).properties["logp"],
        "solubility": solubility(canon).properties["solubility"],
        "toxicity": toxicity(canon).properties["toxicity"],
    })

df = pd.DataFrame(rows)
hits = df[(df.logp.between(0, 5)) & (df.solubility > -4) & (df.toxicity < 0.3)]
print(len(df), "->", len(hits))
# 12000 -> 1843
```

## Similarity search over embeddings

**Problem:** find analogues of a lead compound. **Uses:** Khaos, RDKit and FAISS.

```python theme={null}
import khaos
import faiss
import numpy as np
from rdkit import Chem

embed = khaos.load("chem_mol_embedding")

def vec(smiles):
    return embed(Chem.MolToSmiles(Chem.MolFromSmiles(smiles))).vector

library = np.stack([vec(s) for s in library_smiles]).astype("float32")
faiss.normalize_L2(library)
index = faiss.IndexFlatIP(library.shape[1])
index.add(library)

q = vec("CC(=O)OC1=CC=CC=C1C(=O)O").astype("float32")[None]
faiss.normalize_L2(q)
scores, ids = index.search(q, 5)
print([library_smiles[i] for i in ids[0]])
# ['CC(=O)Oc1ccccc1C(=O)O', 'OC(=O)c1ccccc1O', ...]
```

## Profile a lead compound

**Problem:** get a quick property profile for one molecule. **Uses:** Khaos alone.

```python theme={null}
import khaos

smiles = "CC(=O)OC1=CC=CC=C1C(=O)O"
profile = {
    "logp": khaos.load("chem_logp")(smiles).properties["logp"],
    "solubility": khaos.load("chem_solubility")(smiles).properties["solubility"],
    "toxicity": khaos.load("chem_toxicity")(smiles).properties["toxicity"],
}
print(profile)
# {'logp': 1.19, 'solubility': -1.72, 'toxicity': 0.12}
```

## Inputs and outputs for each model

These are real outputs of the v1 models, run through their exported ONNX files on held-out examples. The shapes listed are the exact ONNX inputs and outputs; `batch` and other named sizes are dynamic.

### `chem_mol_embedding`

A molecule is given as a SMILES string. It is turned into token ids, per-atom features and a bond adjacency matrix (the `featurize` function in `training/chem/train.py`), and the model returns one 256-dimensional vector.

**Model inputs:** `tokens int64 [batch, length]; atoms float32 [batch, atoms, 32]; adj float32 [batch, atoms, atoms]; atom_mask float32 [batch, atoms]`\
**Model outputs:** `vector float32 [batch, 256]`

**Input**

```python theme={null}
smiles = "CC(=O)OC1=CC=CC=C1C(=O)O"   # aspirin
```

**Output**

```json theme={null}
{
  "vector": [
    0.151,
    0.196,
    -0.804,
    -0.971,
    -0.1,
    -0.26,
    "..."
  ],
  "shape": [
    1,
    256
  ],
  "cosine similarity to salicylic acid": 0.848,
  "cosine similarity to hexane": 0.581
}
```

### `chem_logp`

A SMILES string in, one number out. The model's output is standardized; multiplying by `target_std` and adding `target_mean` from `manifest.json` gives the value in real units.

**Model inputs:** `tokens int64 [batch, length]; atoms float32 [batch, atoms, 32]; adj float32 [batch, atoms, atoms]; atom_mask float32 [batch, atoms]`\
**Model outputs:** `value float32 [batch, 1]`

**Input**

```python theme={null}
smiles = "O=C(NNC(=O)c1cc(-c2ccc(Cl)cc2)nc2ccccc12)c1ccoc1"
```

**Output**

```json theme={null}
{
  "logp_predicted": 4.227,
  "logp_in_dataset": 4.223,
  "raw_model_output": 0.994
}
```

### `chem_solubility`

A SMILES string in, one number out. The model's output is standardized; multiplying by `target_std` and adding `target_mean` from `manifest.json` gives the value in real units.

**Model inputs:** `tokens int64 [batch, length]; atoms float32 [batch, atoms, 32]; adj float32 [batch, atoms, atoms]; atom_mask float32 [batch, atoms]`\
**Model outputs:** `value float32 [batch, 1]`

**Input**

```python theme={null}
smiles = "COC(=O)c1ccccc1OC1OC(COC2OCC(O)C(O)C2O)C(O)C(O)C1O"
```

**Output**

```json theme={null}
{
  "logS_predicted": -1.291,
  "logS_in_dataset": -0.742,
  "raw_model_output": 0.624
}
```

### `chem_toxicity`

A SMILES string in, the probability of activity in 12 Tox21 assays plus ClinTox clinical-trial toxicity out. The four highest are shown, with the dataset's measured label (`null` where it is unknown).

**Model inputs:** `tokens int64 [batch, length]; atoms float32 [batch, atoms, 32]; adj float32 [batch, atoms, atoms]; atom_mask float32 [batch, atoms]`\
**Model outputs:** `value float32 [batch, 13]`

**Input**

```python theme={null}
smiles = "C[C@]12CCC(=O)C=C1C=C[C@@H]1[C@@H]2CC[C@@]2(C)[C@H]1CC[C@@]21CCC(=O)O1"
```

**Output**

```json theme={null}
{
  "top_4_of_13": {
    "NR-AR": {
      "probability": 0.939,
      "label": 1
    },
    "NR-AR-LBD": {
      "probability": 0.893,
      "label": 1
    },
    "NR-ER": {
      "probability": 0.71,
      "label": null
    },
    "NR-ER-LBD": {
      "probability": 0.62,
      "label": 0
    }
  }
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.