Python

Selection builder

Build, validate, export, and replay molecule-selection/1 without local chemistry.

Suggest an edit

A selection describes which molecules you want from a chemical space, in four parts:

PartQuestion it answersBuilder methods
strategyHow is the space explored?.ranked(), .sample()
constraintsWhat is allowed? (hard gates).where(), .require_preset(), .require_pattern(), .require_different_scaffold()
objectivesWhat is better? (ranking).maximize_similarity()
portfolioWhat set do I get back?.limit(), .max_per_scaffold()

The builder does no chemistry locally. It builds the selection; the service validates, estimates, and executes it. The builder does not infer shape versus electrostatic, logP versus logD, scaffold method, matching policy, or predictive model: you choose each one explicitly.

The examples below are shown as they appear in a Jupyter notebook. They assume you are signed in (see the Python quickstart).

1. Your first selection

Similar to aspirin by ECFP4, 5 results. Builder methods return a new selection each time, so a chain reads like a sentence.

import pandas as pd
from deepmedchem import Client, Selection

aspirin = "CC(=O)Oc1ccccc1C(=O)O"

selection = (
    Selection.from_database("enamine")                      # which chemical space
    .reference("aspirin", smiles=aspirin)                   # a named query molecule
    .ranked()                                               # strategy: rank by objective
    .maximize_similarity("rdkit.ecfp4_tanimoto", reference="aspirin")
    .limit(5)
)
print(selection.to_yaml())
schema_version: molecule-selection/1
database:
  database_id: enamine-real-v5a
references:
- id: aspirin
  structure:
    format: smiles
    value: CC(=O)Oc1ccccc1C(=O)O
strategy:
  type: ranked
constraints: {}
objectives:
- type: similarity
  reference_id: aspirin
  metric_id: rdkit.ecfp4_tanimoto
  direction: maximize
portfolio:
  limit: 5
execution:
  quality: balanced
include: []

Client() is a signed-in connection to the DeepMedChem API. Every call goes through it. Creating it sends no request. It reads your key (from deepmedchem login or DEEPMEDCHEM_API_KEY) and opens a connection that later calls can reuse. Selections are available on a client, as client.selections.

client = Client()   # close it with client.close(), or use `with Client() as client:`

result = client.selections.create(selection)
result
SelectionResult(5 molecules, method=None, database=None)

The result is the same kind of object as a search result: a list of SMILES with typed hits.

pd.DataFrame({"smiles": result.smiles, "score": result.scores, "price_usd": result.prices})
                             smiles     score  price_usd
0             O=C(O)Oc1ccccc1C(=O)O  0.703704        245
1            COC(=O)Oc1ccccc1C(=O)O  0.666667        163
2     CC(C)(C)OC(=O)Oc1ccccc1C(=O)O  0.606061        163
3             CC(=O)c1ccccc1OC(=O)O  0.600000        245
4  CC(=O)Oc1cccc(C(=O)Oc2ccccc2)c1C  0.555556        163

2. Objectives: what “better” means

An objective ranks the molecules that already pass your constraints, using a reference molecule and a metric you choose (rdkit.ecfp4_tanimoto, cheese.shape or cheese.electrostatic), and it never excludes any of them. See Search methods in the Python quickstart for how they differ.

shape = (
    Selection.from_database("enamine")
    .reference("aspirin", smiles=aspirin)
    .maximize_similarity("cheese.shape", reference="aspirin")
    .limit(5)
)
r = client.selections.create(shape)
pd.DataFrame({"smiles": r.smiles, "shape score": r.scores})
                   smiles  shape score
0   O=C(O)Oc1ccccc1C(=O)O     0.972565
1  COC(=O)Oc1ccccc1C(=O)O     0.971898
2  COC(=O)Oc1ccccc1C(C)=O     0.955080
3   CC(=O)c1ccccc1OC(=O)O     0.924291
4  O=C(O)COc1ccccc1C(=O)O     0.871286

3. Constraints: what is allowed

Constraints are hard gates verified on every returned product; objectives only rank. Approximate synthon-level descriptors may speed up candidate acquisition, but each returned molecule is checked exactly. The registry of property IDs comes from the catalog and depends on what the respective database supports:

space = next(l for l in client.catalog()["libraries"] if l["database_id"] == "enamine-real-v5a")
pd.DataFrame(space["properties"]).rename(columns={"legacy_name": "RDKit name"})
             property_id         RDKit name  units
0           rdkit.mol_wt              MolWt     Da
1     rdkit.crippen_logp            MolLogP      1
2              rdkit.hbd         NumHDonors  count
3              rdkit.hba      NumHAcceptors  count
4  rdkit.rotatable_bonds  NumRotatableBonds  count
5             rdkit.tpsa               TPSA    A^2
6    rdkit.fraction_csp3       FractionCSP3      1
7   rdkit.aromatic_rings   NumAromaticRings  count

Property constraints .where()

Exactly one operator: gt, gte, lt, lte, or range=(low, high). units is required and checked against the registry. fidelity defaults to exact_product and missing to reject.

mw_window = selection.where("rdkit.mol_wt", range=(250, 350), units="Da").include("properties")
r = client.selections.create(mw_window)
pd.DataFrame({"smiles": r.smiles, "MW": [round(h.properties["MolWt"]) for h in r.hits]})
                              smiles   MW
0   CC(=O)Oc1cccc(C(=O)Oc2ccccc2)c1C  270
1  CC(=O)Oc1cccc(C(=O)Oc2ccccc2C)c1C  284
2  CC(=O)Oc1cccc(C(=O)OCc2ccccc2)c1C  284
3     CC(C)(C)OC(=O)COc1ccccc1C(=O)O  252
4     CC(C)(C)OC(=O)NOc1ccccc1C(=O)O  253

Returned properties use RDKit names (MolWt, MolLogP, …).

Presets .require_preset()

A preset is a named bundle of ordinary constraints. lipinski-ro5/v1 is MW ≤ 500 Da, Crippen cLogP ≤ 5, HBD ≤ 5, and HBA ≤ 10, with no unannounced extra rule. The service expands the preset, so you can see exactly what you asked for:

lipinski = selection.require_preset("lipinski-ro5/v1")
normalized = client.selections.validate(lipinski).normalized_selection
pd.DataFrame(normalized["constraints"]["properties"])[["property_id", "operator", "value", "units"]]
          property_id operator  value  units
0        rdkit.mol_wt      lte  500.0     Da
1  rdkit.crippen_logp      lte    5.0      1
2           rdkit.hbd      lte    5.0  count
3           rdkit.hba      lte   10.0  count

Explicit constraints intersect with preset constraints; an empty intersection is a validation error.

Structure and relationship constraints

require_pattern() takes a reviewed pattern ID; require_different_scaffold() compares to a reference using an explicit scaffold method. Evidence can be returned with include("constraint_evidence").

scaffold_hop = (
    selection
    .require_different_scaffold("rdkit.bemis_murcko", reference="aspirin")
    .require_pattern("alpha-amino-acid/v1", min_count=1)
    .include("constraint_evidence")
)
r = client.selections.create(scaffold_hop)
r.smiles
['CC(=O)NC(C(=O)NCCOc1ccccc1C(=O)O)c1ccccc1',
 'CC(=O)N[C@H](Cc1ccccc1)C(=O)NCCOc1ccccc1C(=O)O',
 'O=C(COc1ccccc1C(=O)O)NC(C(=O)O)c1ccccc1',
 'O=C(COc1ccccc1C(=O)O)N[C@H](C(=O)O)c1ccccc1',
 'O=C(COc1ccccc1C(=O)O)N[C@@H](C(=O)O)c1ccccc1']

Each hit reports which constraints it satisfied:

r.hits[0].raw["constraint_evidence"]
[{'constraint_id': 'alpha-amino-acid', 'type': 'structure', 'match_count': 1, 'passed': True},
 {'constraint_id': 'scaffold-0', 'type': 'scaffold_relation', 'operator': 'different', 'passed': True}]

4. Portfolio: the returned set

.limit(n) (1–1000) bounds the set; .max_per_scaffold(n) caps how many hits share a Bemis–Murcko scaffold. These rules run after eligibility and ranking, so they never turn a hard constraint into a preference.

diverse = selection.limit(10).max_per_scaffold(1)
r = client.selections.create(diverse)
len(r), len(set(r.smiles))
(10, 10)

5. No-reference selections: constrained sampling

.sample() replaces ranking by a draw from the space's advertised distribution, conditioned on your constraints. It is not “draw random molecules, then filter”. A seed is reproducible only with the same database release and sampling algorithm version.

sampled = (
    Selection.from_database("enamine")
    .sample(seed=42)
    .require_preset("lipinski-ro5/v1")
    .limit(5)
)
r = client.selections.create(sampled)
r.smiles
['COC(C(=O)N1CCC(CCC(=O)c2cnc(C3CC3)o2)C1)C(=O)N1CCC(O)C(F)C1',
 'CCCn1nnnc1C(N1CCN(C)C(CC)C1)C(C)(C)c1ccccc1',
 'C[C@H]1C(CNC(=O)C[C@@H](NC(=O)c2ccc(Cl)cn2)C2CC2)[C@@H]1C',
 'CCOC(=O)N(C)CC(=O)N(C)CC1CN(c2nc(C)nc3c2CCCC3)CCO1',
 'COc1ccsc1CN(CCC1(O)CCOC1)C(=O)[C@H](O)C(C)(C)C']

6. Copy-on-write: experimental arms from one base

Every method returns a new object, so one base selection can safely fan out.

base = selection.require_preset("lipinski-ro5/v1")
arms = {
    "small":  base.where("rdkit.mol_wt", lte=300, units="Da"),
    "lipophilic": base.where("rdkit.crippen_logp", gte=3, units="1"),
}
rows = []
for name, arm in arms.items():
    r = client.selections.create(arm.include("properties"))
    rows += [(name, h.smiles, round(h.score, 2), round(h.properties["MolWt"]), round(h.properties["MolLogP"], 1)) for h in r.hits[:3]]
pd.DataFrame(rows, columns=["arm", "smiles", "ecfp4", "MW", "cLogP"])
          arm                                            smiles  ecfp4   MW  cLogP
0       small                             O=C(O)Oc1ccccc1C(=O)O   0.70  182    1.4
1       small                            COC(=O)Oc1ccccc1C(=O)O   0.67  196    1.5
2       small                     CC(C)(C)OC(=O)Oc1ccccc1C(=O)O   0.61  238    2.7
3  lipophilic                  CC(=O)Oc1cccc(C(=O)Oc2ccccc2)c1C   0.56  270    3.1
4  lipophilic  CC(=O)Oc1cccc(C(=O)Oc2cccc(C(=O)c3ccccc3)c2C)c1C   0.53  388    4.7
5  lipophilic                 CC(=O)Oc1cccc(C(=O)Oc2ccccc2C)c1C   0.51  284    3.4

The base is unchanged by either arm:

base.to_dict()["constraints"]
{'presets': [{'preset_id': 'lipinski-ro5', 'version': '1'}]}

7. Export and replay

A selection is a plain document (schema molecule-selection/1) in JSON or YAML: store it, review it, send it to a colleague, rerun it.

text = scaffold_hop.to_json(indent=None)
print(text[:160], "...")
{"constraints": {"relationships": [{"method_id": "rdkit.bemis_murcko", "operator": "different", "reference_id": "aspirin", "type": "scaffold_relation"}], "struc ...
replayed = Selection.model_validate(scaffold_hop.to_dict())
replayed.to_dict() == scaffold_hop.to_dict()
True

8. Validate before spending work

Local checks only catch malformed documents; remote validate resolves release-specific capabilities and tells you, per constraint, how it will be executed.

v = client.selections.validate(lipinski)
v.valid, v.selection_hash[:12], v.warnings
(True, '906f1e40537f', [])
pd.DataFrame(v.constraint_execution)
                        path                             status                                           message
0  constraints.properties[0]  conservative_approximate_pushdown  Every returned assembled product is verified e...
1  constraints.properties[1]  conservative_approximate_pushdown  Every returned assembled product is verified e...
2  constraints.properties[2]  conservative_approximate_pushdown  Every returned assembled product is verified e...
3  constraints.properties[3]  conservative_approximate_pushdown  Every returned assembled product is verified e...

Each condition is reported as exact pushdown, conservative approximate pushdown plus exact final verification, post-assembly only, or unsupported.

Local errors (raised immediately, no request)

def attempt(label, fn):
    try:
        fn()
    except ValueError as e:                      # pydantic.ValidationError is a ValueError too
        print(f"{label:24} -> {str(e).splitlines()[0]}")

attempt("limit too large",   lambda: selection.limit(5000))
attempt("preset w/o version", lambda: selection.require_preset("lipinski-ro5"))
attempt("two operators",     lambda: selection.where("rdkit.mol_wt", gt=1, lt=2, units="Da"))
attempt("duplicate ref id",  lambda: selection.reference("aspirin", smiles="C"))
attempt("acquire on sample", lambda: sampled.acquire_predicted_property("openadmet-herg-pchembl", direction="minimize", keep_fraction=0.5))
limit too large          -> selection limit must be between 1 and 1,000
preset w/o version       -> preset must include a version, for example lipinski-ro5/v1
two operators            -> provide exactly one of gt, gte, lt, lte, or range
duplicate ref id         -> duplicate reference ID: aspirin
acquire on sample        -> predicted-property acquisition requires ranked strategy

Remote errors (the service knows the registries)

from deepmedchem import DeepMedChemError

problems = {
    "unknown property": selection.where("rdkit.nope", gt=1, units="Da"),
    "wrong units":      selection.where("rdkit.mol_wt", gt=1, units="kg"),
    "contradiction":    selection.require_preset("lipinski-ro5/v1").where("rdkit.mol_wt", gt=600, units="Da"),
}
for label, bad in problems.items():
    try:
        client.selections.validate(bad)
    except DeepMedChemError as e:
        print(f"{label:18} {e.code} (HTTP {e.status_code}): {e}")
unknown property   invalid_request (HTTP 400): unsupported property_id: rdkit.nope
wrong units        invalid_request (HTTP 400): rdkit.mol_wt requires units 'Da', got 'kg'
contradiction      invalid_request (HTTP 400): contradictory constraints for rdkit.mol_wt

9. Estimate: synchronous or durable?

estimate says how the work must run. Small, single-reference selections are synchronous; anything over the budget needs a durable run. The service never silently runs a hidden job or relaxes a condition.

def tier(sel):
    e = client.selections.estimate(sel)
    return e.execution_tier, e.work["reason"]

pd.DataFrame(
    [
        ("5 hits, one objective", *tier(selection)),
        ("1000 hits",             *tier(selection.limit(1000))),
    ],
    columns=["selection", "tier", "reason"],
)
               selection         tier                                         reason
0  5 hits, one objective  synchronous          within synchronous execution contract
1              1000 hits      durable  portfolio limit exceeds synchronous limit 200

A durable estimate is a successful answer, not an error. It carries a reusable run/1 request:

est = client.selections.estimate(selection.limit(1000))
if est.execution_tier == "synchronous":
    result = client.selections.create(est.normalized_selection)
else:
    # a durable estimate carries a ready-to-use run/1 request
    print("durable; reusable run request available:", est.reusable_run_request is not None)
durable; reusable run request available: True

Sending an over-budget selection straight to create is refused, not silently run:

try:
    client.selections.create(selection.limit(1000))
except DeepMedChemError as e:
    print(e.code, e.status_code)
durable_required 413

10. Read the result

create returns a normal result (list of SMILES, typed hits) plus the normalized selection, its hash, and counts that explain what the engine did.

r = client.selections.create(lipinski.include("properties"))
r.status, r.id[:12], r.selection_hash[:12], r.database_release
('completed', 'sel_2af11d1e', '2af11d1e99e0', '2026-09-06.2')
# what the engine did: proposals in, assembled products, dropped by exact checks, returned
pd.Series(r.counts, name="count").to_frame()
                              count
proposed                        100
normalized_candidates           100
approximate_property_dropped      0
approximate_admet_dropped         0
assembly_attempted              100
assembly_failed                  51
duplicate_products                0
admet_out_of_domain               0
exact_property_dropped            0
exact_constraint_dropped          0
exact_admet_scored                0
exact_admet_dropped               0
returned                          5
refill_rounds                     1
candidates_considered           100
stop_reason          target_reached
pd.DataFrame([h.properties for h in r.hits]).assign(smiles=r.smiles).round(1)
   MolWt  MolLogP  NumHDonors  NumHAcceptors                            smiles
0  182.1      1.4         2.0            3.0             O=C(O)Oc1ccccc1C(=O)O
1  196.2      1.5         1.0            4.0            COC(=O)Oc1ccccc1C(=O)O
2  238.2      2.7         1.0            4.0     CC(C)(C)OC(=O)Oc1ccccc1C(=O)O
3  180.2      1.9         1.0            3.0             CC(=O)c1ccccc1OC(=O)O
4  270.3      3.1         0.0            4.0  CC(=O)Oc1cccc(C(=O)Oc2ccccc2)c1C

11. Predicted-property shortlist acquisition (experimental)

acquire_predicted_property keeps the best rank quantile of a similarity shortlist for an advertised predicted endpoint (here: hERG pChEMBL, lower is better). It is available only for ranked selections that already have a similarity objective. It is an acquisition signal, not a hard ADMET constraint, and the values are predictions, not assays. Use exact RDKit constraints (section 3) for eligibility.

Endpoint support is release-specific, so check which endpoints a database advertises:

pd.DataFrame(space["predicted_property_endpoints"])[["endpoint_id", "units", "qualification"]].head(6)
                       endpoint_id             units                  qualification
0   openadmet-caco2-a-to-b-logpapp       log10(cm/s)  experimental-acquisition-only
1   openadmet-caco2-b-to-a-logpapp       log10(cm/s)  experimental-acquisition-only
2  openadmet-clint-human-microsome  log10(uL/min/mg)  experimental-acquisition-only
3  openadmet-clint-mouse-microsome  log10(uL/min/mg)  experimental-acquisition-only
4    openadmet-clint-rat-microsome  log10(uL/min/mg)  experimental-acquisition-only
5         openadmet-cyp1a2-logac50      log10(molar)  experimental-acquisition-only
herg = selection.acquire_predicted_property(
    "openadmet-herg-pchembl", direction="minimize", keep_fraction=0.25
)
r = client.selections.create(herg)
a = r.acquisition
print(f"{a.candidates_before} candidates -> {a.candidates_after} kept ({a.direction} {a.endpoint_id}, {a.units})")
print(a.qualification, "| model:", a.predicted_model_version)
100 candidates -> 25 kept (minimize openadmet-herg-pchembl, pChEMBL)
experimental-acquisition-only | model: herg-chemeleon-baseline@93f6527a4766

Per-hit predicted values and their applicability come with response-level model version, direction, units, qualification, and candidate counts:

pd.DataFrame(
    {
        "smiles": r.smiles,
        "ecfp4": [round(h.score, 2) for h in r.hits],
        "predicted hERG pChEMBL": [round(h.acquisition.predicted_value, 2) for h in r.hits],
        "in domain": [h.acquisition.applicable for h in r.hits],
    }
)
                     smiles  ecfp4  predicted hERG pChEMBL  in domain
0     O=C(O)Oc1ccccc1C(=O)O   0.70                    4.54       True
1    COC(=O)Oc1ccccc1C(=O)O   0.67                    4.70       True
2     CC(=O)c1ccccc1OC(=O)O   0.60                    4.30       True
3    O=C(O)COc1ccccc1C(=O)O   0.53                    4.28       True
4  O=C(O)CCCOc1ccccc1C(=O)O   0.49                    3.24       True

12. Pinning a release

Selection.from_database(db, release=...) pins the release, so a selection can be rerun against the same data. Without it the current release is used. Either way, the result reports the release it searched; store it together with the selection hash.

current = space["release_id"]
for release in [None, current]:
    sel = (Selection.from_database("enamine", release=release)
           .reference("a", smiles=aspirin)
           .maximize_similarity("rdkit.ecfp4_tanimoto", reference="a").limit(1))
    r = client.selections.create(sel)
    print(f"requested={release!s:12} searched={r.database_release}")
requested=None         searched=2026-09-06.2
requested=2026-09-06.2 searched=2026-09-06.2
client.close()

On this page