atommapper 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Charlles Abreu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,319 @@
1
+ Metadata-Version: 2.4
2
+ Name: atommapper
3
+ Version: 0.1.0
4
+ Requires-Dist: rdkit>=2025.3
5
+ Requires-Dist: networkx>=3.2
6
+ Requires-Dist: scipy>=1.11
7
+ Requires-Dist: ruff>=0.15 ; extra == 'dev'
8
+ Requires-Dist: ty>=0.0.90 ; extra == 'dev'
9
+ Requires-Dist: pre-commit>=4 ; extra == 'dev'
10
+ Requires-Dist: pytest>=8 ; extra == 'test'
11
+ Provides-Extra: dev
12
+ Provides-Extra: test
13
+ License-File: LICENSE
14
+ Summary: Fast atom mapping for related molecules, with mapped SMILES and structured atom and bond changes
15
+ License-Expression: MIT
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
18
+ Project-URL: Documentation, https://github.com/craabreu/atommapper#readme
19
+ Project-URL: Homepage, https://github.com/craabreu/atommapper
20
+ Project-URL: Issues, https://github.com/craabreu/atommapper/issues
21
+ Project-URL: Repository, https://github.com/craabreu/atommapper
22
+
23
+ # AtomMapper
24
+
25
+ **Fast atom mapping for pairs of related molecules.** AtomMapper identifies a shared
26
+ core and reports which atoms and bonds are added, removed, or changed. It accepts SMILES
27
+ strings or RDKit molecules and returns an atom correspondence, a mapped reaction SMILES,
28
+ and a structured list of changes. No 3D coordinates are needed.
29
+
30
+ AtomMapper follows mapping constraints based on OpenFE's LOMAP: a connected core,
31
+ complete rings, and preserved stereochemistry by default. Its search engine is written
32
+ in Rust, with a Python API and command-line interface.
33
+
34
+ **In the included benchmarks, AtomMapper used 17–102× less total mapping time than
35
+ LOMAP's mapping step** across 3,529 molecular pairs. Most of the gain comes from avoiding
36
+ LOMAP's slowest searches; the median per-pair speedup was 1.1–2.3×. With the bond-maximizing
37
+ objective, 95–98% of mappings agreed with LOMAP up to symmetry, excluding LOMAP timeouts.
38
+ These measurements cover mapping, not similarity scoring or network planning.
39
+ See the [benchmark results and methodology](https://github.com/craabreu/atommapper/blob/main/benchmarks/README.md).
40
+
41
+ <p align="center">
42
+ <img src="https://raw.githubusercontent.com/craabreu/atommapper/main/docs/images/example.png" width="820"
43
+ alt="Two EG5 ligands with their shared core aligned and atoms and bonds highlighted as removed, added, or changed">
44
+ </p>
45
+
46
+ *Two EG5 ligands from the protein-ligand benchmark. The shared core is aligned; colors
47
+ show removed, added, and changed atoms and bonds. AtomMapper can generate these drawings
48
+ from either the command line or Python.*
49
+
50
+ ## Installation
51
+
52
+ Requires **Python 3.11 or later**.
53
+
54
+ ```bash
55
+ python -m pip install atommapper
56
+ ```
57
+
58
+ Wheels are available for Linux (x86_64 and aarch64), macOS (Intel and Apple silicon), and
59
+ Windows (x64). RDKit, NetworkX, and SciPy are installed as dependencies. If pip builds from
60
+ source instead of installing a compatible wheel, you also need a
61
+ [Rust toolchain](https://rustup.rs). For an editable checkout, see [Development](#development).
62
+
63
+ ## Quick start
64
+
65
+ ### Python
66
+
67
+ ```python
68
+ from atommapper import map_atoms
69
+
70
+ result = map_atoms("Cc1ccc(F)cc1", "Cc1cccc(F)c1")
71
+
72
+ print(result.status) # complete
73
+ print(result.metadata["size"]) # 4: one atom and one bond removed, one of each added
74
+ print(result.reaction_smiles)
75
+
76
+ # Zero-based atom indices: source atom -> target atom
77
+ atom_map = {atom.source_index: atom.target_index for atom in result.mapping}
78
+ ```
79
+
80
+ Each entry in `result.mapping` connects a source atom to a target atom. A mapped atom
81
+ can change element by default; use `element_change=False` to require matching elements.
82
+ Atoms outside the mapping are reported in `result.atom_changes`, and bond changes in
83
+ `result.bond_changes`.
84
+
85
+ You can also pass RDKit `Chem.Mol` objects directly. The input molecules are copied,
86
+ not modified, and existing atom-map numbers are ignored. Returned indices refer to the
87
+ input molecules; for SMILES, they follow RDKit's parsing order with explicit hydrogens
88
+ retained. Ordinary explicit hydrogens are then merged into their attached atoms for the
89
+ search. Pass `Chem.Mol` objects when you need indices tied to molecules already in your
90
+ workflow.
91
+
92
+ ### Command line
93
+
94
+ ```bash
95
+ atommapper "Cc1ccc(F)cc1" "Cc1cccc(F)c1"
96
+ ```
97
+
98
+ ```text
99
+ [CH3:1][c:6]1[cH:2][cH:4][c:7]([F:8])[cH:5][cH:3]1>>[CH3:1][c:6]1[cH:2][cH:4][cH:7][c:5]([F:9])[cH:3]1
100
+ ```
101
+
102
+ The same atom-map number on both sides identifies a mapped pair. A number on only one
103
+ side identifies a removed or added atom: here, fluorine 8 is removed and fluorine 9 is
104
+ added. These **one-based identifiers are different from the zero-based input indices**.
105
+ The `source>>target` notation describes the correspondence; it does not predict a chemical
106
+ reaction or mechanism.
107
+
108
+ ```bash
109
+ # Full result, including status, atom indices, changes, and search metadata
110
+ atommapper "CCO" "CC=O" --json
111
+
112
+ # Save a drawing as well as printing the mapped SMILES
113
+ atommapper "Cc1ccc(F)cc1" "Cc1cccc(F)c1" --draw walk.svg --numbers
114
+
115
+ atommapper --help
116
+ ```
117
+
118
+ ## Choosing a mapping
119
+
120
+ ```text
121
+ map_atoms(source, target, *, element_change=True, objective="change",
122
+ allow_stereo_inversion=False, settings=None)
123
+ ```
124
+
125
+ | Option | Default behavior | Alternative |
126
+ |---|---|---|
127
+ | `objective` | `"change"`: minimize the size of the change | `"bonds"`: maximize kept bonds, then kept atoms, then minimize change |
128
+ | `element_change` | `True`: mapped atoms may change element | `False` / `--fixed-elements`: require matching elements |
129
+ | `allow_stereo_inversion` | `False`: reject mappings that invert a retained stereo element | `True` / `--allow-stereo-inversion`: allow inversions and count each as one change |
130
+ | `settings` | Default search budgets and time limit | A `Settings` instance; see [Search limits](#search-limits) |
131
+
132
+ The change size counts each inserted or deleted atom or bond, each element change, and
133
+ each bond-order change as one. Allowed stereo inversions also count as one. Other
134
+ attribute changes, such as charge and hydrogen count, are reported but do not add to this
135
+ objective. Consequently, `metadata["size"]` is **not the number of entries** in the change
136
+ lists, nor a free-energy or chemical-similarity score.
137
+
138
+ For example, pyridine and benzene can keep all six ring atoms with `element_change=True`.
139
+ With `element_change=False`, they have no valid shared core because preserving the five
140
+ carbons alone would leave an incomplete ring.
141
+
142
+ Use `objective="bonds"` (`--objective bonds`) for a bond-maximizing comparison with LOMAP.
143
+ AtomMapper applies constraints during its search and uses stricter stereo checks, so
144
+ identical mappings are not guaranteed. It does not provide LOMAP's hydrogen mapping,
145
+ similarity scores, or network planner.
146
+
147
+ ## Drawings and notebooks
148
+
149
+ A `MappingResult` displays as an SVG drawing in notebooks. To save or render it explicitly:
150
+
151
+ ```python
152
+ from atommapper import draw_png, draw_svg, map_atoms, save_image
153
+
154
+ result = map_atoms("Cc1ccc(F)cc1", "Cc1cccc(F)c1")
155
+ svg = draw_svg(result, width=400, height=300) # SVG text
156
+ png = draw_png(result, numbers=True) # PNG bytes
157
+ save_image(result, "walk.svg") # .svg or .png selects the format
158
+ ```
159
+
160
+ The source and target appear side by side with their shared atoms aligned. Each panel is
161
+ 400 × 300 pixels by default, with a legend below. Set `width` and `height` in Python or
162
+ `--size 400x300` on the command line to change the panel size.
163
+
164
+ Removed atoms and bonds are vermillion, additions are blue, and changes are yellow.
165
+ Hydrogen-count changes are omitted from the highlights. Stereo inversions carry R/S or
166
+ E/Z labels; preserving double-bond geometry can require moving some mapped atoms out of
167
+ alignment. `numbers=True` (`--numbers`) labels mapped atoms with their identifiers.
168
+
169
+ ## Working with results
170
+
171
+ `map_atoms` returns a `MappingResult`:
172
+
173
+ | Field | Meaning |
174
+ |---|---|
175
+ | `reaction_smiles` | Mapped `source>>target` SMILES; mapped atoms are numbered first, then source-only and target-only atoms |
176
+ | `mapping` | Tuple of `MappedAtom(identifier, source_index, target_index, tag)` records |
177
+ | `atom_changes`, `bond_changes` | Changes keyed by the identifiers in `reaction_smiles` |
178
+ | `status`, `reason` | Search outcome and an explanation when applicable |
179
+ | `metadata` | Change size, kept counts, optimality, stereo verdicts, checks, budgets, timings, settings, and dependency versions |
180
+
181
+ The mapping tag is `seed` or `refined`, indicating how an atom entered the search; it is
182
+ not a confidence score. `result.reverse()` swaps the two sides and renumbers the result
183
+ without searching again. `result.to_dict()` returns the public fields as plain Python
184
+ data for serialization.
185
+
186
+ Check `status` before using a result in an automated workflow:
187
+
188
+ | Status | Meaning |
189
+ |---|---|
190
+ | `complete` | The configured search finished; global optimality is not guaranteed |
191
+ | `timed_out` | A work budget, size ceiling, or time limit stopped the search; the result is the best found so far |
192
+ | `no_common_vertices` | No atom can be mapped under the constraints; the mapping is empty |
193
+ | `unsupported_input` | A valid input cannot be represented faithfully; `reason` explains why, and no mapped SMILES is returned |
194
+
195
+ ```python
196
+ from atommapper import InvalidInput, Settings, map_atoms
197
+
198
+ try:
199
+ result = map_atoms("CCO", "CC=O", settings=Settings(time_limit_s=10.0))
200
+ except InvalidInput as error:
201
+ print(f"Invalid molecule: {error}")
202
+ else:
203
+ if result.status == "unsupported_input":
204
+ print(result.reason)
205
+ elif result.status == "timed_out":
206
+ print("Partial result:", result.metadata["budget"]["stopped_by"])
207
+ else:
208
+ print(result.reaction_smiles)
209
+ ```
210
+
211
+ Invalid or empty molecules raise `InvalidInput` (a `ValueError` subclass). An unknown
212
+ objective raises `ValueError`; invalid `Settings` values raise `TypeError` or `ValueError`.
213
+ A charged hydrogen attached to a heavy atom is an example of an unsupported input.
214
+
215
+ The CLI exits with **0** for a completed search (including an empty mapping), **1** for
216
+ invalid or unsupported input, **2** for argument-parsing errors, and **3** for a search
217
+ stopped by a limit. A partial result is still printed; `--accept-partial` changes its exit
218
+ code to 0, but does not change the result's status.
219
+
220
+ ## Mapping constraints
221
+
222
+ - **Connected core.** Mapped atoms joined by retained bonds form one connected component.
223
+ Atoms isolated on both sides, such as counterions, are exempt.
224
+ - **Ring membership.** Ring atoms map only to ring atoms; chain atoms only to chain atoms.
225
+ - **Complete rings.** Every retained ring atom and ring bond must lie on a cycle in the
226
+ shared core. A benzene ring can map to one ring of naphthalene, but cyclohexane and
227
+ cyclopentane cannot share a partial ring.
228
+ - **Bonds between mapped atoms.** Two mapped atoms bonded on either side must also be
229
+ bonded on the other side. Bond orders may change, even with fixed elements.
230
+ - **Stereochemistry.** By default, a mapping cannot invert a retained tetrahedral centre
231
+ or double bond. The check uses the mapped neighbours, including attached hydrogens,
232
+ rather than simply comparing R/S labels. Stereo can still be gained or lost and is
233
+ reported in `metadata["stereo"]`.
234
+ - **Hydrogens.** Ordinary attached hydrogens are implicit; changes in their count are
235
+ reported as atom attributes. This is intended for heavy-atom mapping, not a complete
236
+ all-atom correspondence.
237
+
238
+ Ties favor fewer mapped atoms with changed heavy-atom neighbours, then the smaller
239
+ moving group, then canonical order. These choices are designed to give consistent
240
+ mappings when the inputs are reordered or reversed. All benchmark pairs agreed under
241
+ reversal up to symmetry; timeouts and search caps can affect that behavior.
242
+
243
+ ## Search limits
244
+
245
+ ```python
246
+ from atommapper import Settings, map_atoms
247
+
248
+ result = map_atoms(
249
+ "Cc1ccc(F)cc1", "Cc1cccc(F)c1",
250
+ settings=Settings(time_limit_s=30.0, node_budget=2_000_000),
251
+ )
252
+ ```
253
+
254
+ | Setting | Default | Purpose | CLI option |
255
+ |---|---:|---|---|
256
+ | `fragment_steps` | 20,000,000 | Total fragment-search work budget | `--steps` |
257
+ | `node_budget` | 1,000,000 | Total branch-and-bound work budget | `--nodes` |
258
+ | `time_limit_s` | 60.0 | Wall-clock limit measured from the start of the call | `--timeout` |
259
+ | `fragment_bond_pairs` | 20,000 | Ceiling on compatible bond pairs in the fragment search | `--pairs` |
260
+ | `coarse_fragment_steps` | 100,000 | Work cap for the element-independent fragment pass | Python only |
261
+
262
+ Work budgets make the stopping point reproducible, provided the wall-clock limit does
263
+ not intervene. Clock-limited results depend on machine speed and load. The time limit is
264
+ not a hard process deadline: parsing, stereo perception, and result assembly are not
265
+ interrupted. The optional global check described below has its own additional budget.
266
+
267
+ Reaching the coarse-pass cap is part of the normal method and does not set `timed_out`;
268
+ inspect `metadata["fragment_search"]["coarse_capped"]`. The bond-pair ceiling protects
269
+ against large search graphs; increase it if `stopped_by` includes `pairs`.
270
+
271
+ `Settings` also exposes `max_fragments`, `k_seeds`, and `max_alternatives` for advanced
272
+ control of candidate storage and refinement. Restricting seeds or truncating candidates
273
+ can affect mapping quality and consistency under input reversal.
274
+
275
+ ## Optimality and limitations
276
+
277
+ **A completed search is not a proof of the globally best mapping.** AtomMapper starts
278
+ from shared connected fragments, trims them to the constraints, and grows mappings around
279
+ the remaining pieces using branch-and-bound. Each starting piece is held fixed, so the
280
+ usual result is `metadata["optimality"] == "optimal_given_seed"`.
281
+
282
+ The seeds can miss a better mapping, sometimes by a large margin. For example,
283
+ `NC1Cc2ccccc2CCC1=O` to `N[C@H]1CCc2ccccc2C[C@@H]1O` with fixed elements gives a change
284
+ size of 21, although a size of 8 is possible. Extra seeds address common stereo-related
285
+ failures, but do not make the search globally exact. Increasing budgets alone may not
286
+ fix a poor choice of seeds.
287
+
288
+ `Settings(global_budget_s=...)` enables an optional exact lower-bound calculation after
289
+ the search, using unconstrained graph edit distance. If it finishes and matches the
290
+ mapping cost, `optimality` becomes `optimal`. Otherwise, it does not establish optimality.
291
+ This check can be expensive and is intended for small molecules and validation.
292
+
293
+ ## Development
294
+
295
+ Building from source requires Python 3.11+ and Rust:
296
+
297
+ ```bash
298
+ git clone https://github.com/craabreu/atommapper.git
299
+ cd atommapper
300
+ python -m venv .venv
301
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
302
+ python -m pip install -e ".[test,dev]"
303
+
304
+ make check # lint, types, Rust checks and tests, rebuild, Python tests
305
+ make format # format Python and Rust sources
306
+ ```
307
+
308
+ The `make` commands require Make. To run only the Python tests after installation, use
309
+ `python -m pytest -q`. Benchmark dependencies and reproduction commands are documented
310
+ [separately](https://github.com/craabreu/atommapper/blob/main/benchmarks/README.md#reproducing-the-benchmarks).
311
+
312
+ Please report bugs with a minimal pair of input molecules, the mapping options, and
313
+ `result.metadata["versions"]` on the
314
+ [issue tracker](https://github.com/craabreu/atommapper/issues).
315
+
316
+ ## License
317
+
318
+ AtomMapper is released under the [MIT license](https://github.com/craabreu/atommapper/blob/main/LICENSE).
319
+
@@ -0,0 +1,296 @@
1
+ # AtomMapper
2
+
3
+ **Fast atom mapping for pairs of related molecules.** AtomMapper identifies a shared
4
+ core and reports which atoms and bonds are added, removed, or changed. It accepts SMILES
5
+ strings or RDKit molecules and returns an atom correspondence, a mapped reaction SMILES,
6
+ and a structured list of changes. No 3D coordinates are needed.
7
+
8
+ AtomMapper follows mapping constraints based on OpenFE's LOMAP: a connected core,
9
+ complete rings, and preserved stereochemistry by default. Its search engine is written
10
+ in Rust, with a Python API and command-line interface.
11
+
12
+ **In the included benchmarks, AtomMapper used 17–102× less total mapping time than
13
+ LOMAP's mapping step** across 3,529 molecular pairs. Most of the gain comes from avoiding
14
+ LOMAP's slowest searches; the median per-pair speedup was 1.1–2.3×. With the bond-maximizing
15
+ objective, 95–98% of mappings agreed with LOMAP up to symmetry, excluding LOMAP timeouts.
16
+ These measurements cover mapping, not similarity scoring or network planning.
17
+ See the [benchmark results and methodology](https://github.com/craabreu/atommapper/blob/main/benchmarks/README.md).
18
+
19
+ <p align="center">
20
+ <img src="https://raw.githubusercontent.com/craabreu/atommapper/main/docs/images/example.png" width="820"
21
+ alt="Two EG5 ligands with their shared core aligned and atoms and bonds highlighted as removed, added, or changed">
22
+ </p>
23
+
24
+ *Two EG5 ligands from the protein-ligand benchmark. The shared core is aligned; colors
25
+ show removed, added, and changed atoms and bonds. AtomMapper can generate these drawings
26
+ from either the command line or Python.*
27
+
28
+ ## Installation
29
+
30
+ Requires **Python 3.11 or later**.
31
+
32
+ ```bash
33
+ python -m pip install atommapper
34
+ ```
35
+
36
+ Wheels are available for Linux (x86_64 and aarch64), macOS (Intel and Apple silicon), and
37
+ Windows (x64). RDKit, NetworkX, and SciPy are installed as dependencies. If pip builds from
38
+ source instead of installing a compatible wheel, you also need a
39
+ [Rust toolchain](https://rustup.rs). For an editable checkout, see [Development](#development).
40
+
41
+ ## Quick start
42
+
43
+ ### Python
44
+
45
+ ```python
46
+ from atommapper import map_atoms
47
+
48
+ result = map_atoms("Cc1ccc(F)cc1", "Cc1cccc(F)c1")
49
+
50
+ print(result.status) # complete
51
+ print(result.metadata["size"]) # 4: one atom and one bond removed, one of each added
52
+ print(result.reaction_smiles)
53
+
54
+ # Zero-based atom indices: source atom -> target atom
55
+ atom_map = {atom.source_index: atom.target_index for atom in result.mapping}
56
+ ```
57
+
58
+ Each entry in `result.mapping` connects a source atom to a target atom. A mapped atom
59
+ can change element by default; use `element_change=False` to require matching elements.
60
+ Atoms outside the mapping are reported in `result.atom_changes`, and bond changes in
61
+ `result.bond_changes`.
62
+
63
+ You can also pass RDKit `Chem.Mol` objects directly. The input molecules are copied,
64
+ not modified, and existing atom-map numbers are ignored. Returned indices refer to the
65
+ input molecules; for SMILES, they follow RDKit's parsing order with explicit hydrogens
66
+ retained. Ordinary explicit hydrogens are then merged into their attached atoms for the
67
+ search. Pass `Chem.Mol` objects when you need indices tied to molecules already in your
68
+ workflow.
69
+
70
+ ### Command line
71
+
72
+ ```bash
73
+ atommapper "Cc1ccc(F)cc1" "Cc1cccc(F)c1"
74
+ ```
75
+
76
+ ```text
77
+ [CH3:1][c:6]1[cH:2][cH:4][c:7]([F:8])[cH:5][cH:3]1>>[CH3:1][c:6]1[cH:2][cH:4][cH:7][c:5]([F:9])[cH:3]1
78
+ ```
79
+
80
+ The same atom-map number on both sides identifies a mapped pair. A number on only one
81
+ side identifies a removed or added atom: here, fluorine 8 is removed and fluorine 9 is
82
+ added. These **one-based identifiers are different from the zero-based input indices**.
83
+ The `source>>target` notation describes the correspondence; it does not predict a chemical
84
+ reaction or mechanism.
85
+
86
+ ```bash
87
+ # Full result, including status, atom indices, changes, and search metadata
88
+ atommapper "CCO" "CC=O" --json
89
+
90
+ # Save a drawing as well as printing the mapped SMILES
91
+ atommapper "Cc1ccc(F)cc1" "Cc1cccc(F)c1" --draw walk.svg --numbers
92
+
93
+ atommapper --help
94
+ ```
95
+
96
+ ## Choosing a mapping
97
+
98
+ ```text
99
+ map_atoms(source, target, *, element_change=True, objective="change",
100
+ allow_stereo_inversion=False, settings=None)
101
+ ```
102
+
103
+ | Option | Default behavior | Alternative |
104
+ |---|---|---|
105
+ | `objective` | `"change"`: minimize the size of the change | `"bonds"`: maximize kept bonds, then kept atoms, then minimize change |
106
+ | `element_change` | `True`: mapped atoms may change element | `False` / `--fixed-elements`: require matching elements |
107
+ | `allow_stereo_inversion` | `False`: reject mappings that invert a retained stereo element | `True` / `--allow-stereo-inversion`: allow inversions and count each as one change |
108
+ | `settings` | Default search budgets and time limit | A `Settings` instance; see [Search limits](#search-limits) |
109
+
110
+ The change size counts each inserted or deleted atom or bond, each element change, and
111
+ each bond-order change as one. Allowed stereo inversions also count as one. Other
112
+ attribute changes, such as charge and hydrogen count, are reported but do not add to this
113
+ objective. Consequently, `metadata["size"]` is **not the number of entries** in the change
114
+ lists, nor a free-energy or chemical-similarity score.
115
+
116
+ For example, pyridine and benzene can keep all six ring atoms with `element_change=True`.
117
+ With `element_change=False`, they have no valid shared core because preserving the five
118
+ carbons alone would leave an incomplete ring.
119
+
120
+ Use `objective="bonds"` (`--objective bonds`) for a bond-maximizing comparison with LOMAP.
121
+ AtomMapper applies constraints during its search and uses stricter stereo checks, so
122
+ identical mappings are not guaranteed. It does not provide LOMAP's hydrogen mapping,
123
+ similarity scores, or network planner.
124
+
125
+ ## Drawings and notebooks
126
+
127
+ A `MappingResult` displays as an SVG drawing in notebooks. To save or render it explicitly:
128
+
129
+ ```python
130
+ from atommapper import draw_png, draw_svg, map_atoms, save_image
131
+
132
+ result = map_atoms("Cc1ccc(F)cc1", "Cc1cccc(F)c1")
133
+ svg = draw_svg(result, width=400, height=300) # SVG text
134
+ png = draw_png(result, numbers=True) # PNG bytes
135
+ save_image(result, "walk.svg") # .svg or .png selects the format
136
+ ```
137
+
138
+ The source and target appear side by side with their shared atoms aligned. Each panel is
139
+ 400 × 300 pixels by default, with a legend below. Set `width` and `height` in Python or
140
+ `--size 400x300` on the command line to change the panel size.
141
+
142
+ Removed atoms and bonds are vermillion, additions are blue, and changes are yellow.
143
+ Hydrogen-count changes are omitted from the highlights. Stereo inversions carry R/S or
144
+ E/Z labels; preserving double-bond geometry can require moving some mapped atoms out of
145
+ alignment. `numbers=True` (`--numbers`) labels mapped atoms with their identifiers.
146
+
147
+ ## Working with results
148
+
149
+ `map_atoms` returns a `MappingResult`:
150
+
151
+ | Field | Meaning |
152
+ |---|---|
153
+ | `reaction_smiles` | Mapped `source>>target` SMILES; mapped atoms are numbered first, then source-only and target-only atoms |
154
+ | `mapping` | Tuple of `MappedAtom(identifier, source_index, target_index, tag)` records |
155
+ | `atom_changes`, `bond_changes` | Changes keyed by the identifiers in `reaction_smiles` |
156
+ | `status`, `reason` | Search outcome and an explanation when applicable |
157
+ | `metadata` | Change size, kept counts, optimality, stereo verdicts, checks, budgets, timings, settings, and dependency versions |
158
+
159
+ The mapping tag is `seed` or `refined`, indicating how an atom entered the search; it is
160
+ not a confidence score. `result.reverse()` swaps the two sides and renumbers the result
161
+ without searching again. `result.to_dict()` returns the public fields as plain Python
162
+ data for serialization.
163
+
164
+ Check `status` before using a result in an automated workflow:
165
+
166
+ | Status | Meaning |
167
+ |---|---|
168
+ | `complete` | The configured search finished; global optimality is not guaranteed |
169
+ | `timed_out` | A work budget, size ceiling, or time limit stopped the search; the result is the best found so far |
170
+ | `no_common_vertices` | No atom can be mapped under the constraints; the mapping is empty |
171
+ | `unsupported_input` | A valid input cannot be represented faithfully; `reason` explains why, and no mapped SMILES is returned |
172
+
173
+ ```python
174
+ from atommapper import InvalidInput, Settings, map_atoms
175
+
176
+ try:
177
+ result = map_atoms("CCO", "CC=O", settings=Settings(time_limit_s=10.0))
178
+ except InvalidInput as error:
179
+ print(f"Invalid molecule: {error}")
180
+ else:
181
+ if result.status == "unsupported_input":
182
+ print(result.reason)
183
+ elif result.status == "timed_out":
184
+ print("Partial result:", result.metadata["budget"]["stopped_by"])
185
+ else:
186
+ print(result.reaction_smiles)
187
+ ```
188
+
189
+ Invalid or empty molecules raise `InvalidInput` (a `ValueError` subclass). An unknown
190
+ objective raises `ValueError`; invalid `Settings` values raise `TypeError` or `ValueError`.
191
+ A charged hydrogen attached to a heavy atom is an example of an unsupported input.
192
+
193
+ The CLI exits with **0** for a completed search (including an empty mapping), **1** for
194
+ invalid or unsupported input, **2** for argument-parsing errors, and **3** for a search
195
+ stopped by a limit. A partial result is still printed; `--accept-partial` changes its exit
196
+ code to 0, but does not change the result's status.
197
+
198
+ ## Mapping constraints
199
+
200
+ - **Connected core.** Mapped atoms joined by retained bonds form one connected component.
201
+ Atoms isolated on both sides, such as counterions, are exempt.
202
+ - **Ring membership.** Ring atoms map only to ring atoms; chain atoms only to chain atoms.
203
+ - **Complete rings.** Every retained ring atom and ring bond must lie on a cycle in the
204
+ shared core. A benzene ring can map to one ring of naphthalene, but cyclohexane and
205
+ cyclopentane cannot share a partial ring.
206
+ - **Bonds between mapped atoms.** Two mapped atoms bonded on either side must also be
207
+ bonded on the other side. Bond orders may change, even with fixed elements.
208
+ - **Stereochemistry.** By default, a mapping cannot invert a retained tetrahedral centre
209
+ or double bond. The check uses the mapped neighbours, including attached hydrogens,
210
+ rather than simply comparing R/S labels. Stereo can still be gained or lost and is
211
+ reported in `metadata["stereo"]`.
212
+ - **Hydrogens.** Ordinary attached hydrogens are implicit; changes in their count are
213
+ reported as atom attributes. This is intended for heavy-atom mapping, not a complete
214
+ all-atom correspondence.
215
+
216
+ Ties favor fewer mapped atoms with changed heavy-atom neighbours, then the smaller
217
+ moving group, then canonical order. These choices are designed to give consistent
218
+ mappings when the inputs are reordered or reversed. All benchmark pairs agreed under
219
+ reversal up to symmetry; timeouts and search caps can affect that behavior.
220
+
221
+ ## Search limits
222
+
223
+ ```python
224
+ from atommapper import Settings, map_atoms
225
+
226
+ result = map_atoms(
227
+ "Cc1ccc(F)cc1", "Cc1cccc(F)c1",
228
+ settings=Settings(time_limit_s=30.0, node_budget=2_000_000),
229
+ )
230
+ ```
231
+
232
+ | Setting | Default | Purpose | CLI option |
233
+ |---|---:|---|---|
234
+ | `fragment_steps` | 20,000,000 | Total fragment-search work budget | `--steps` |
235
+ | `node_budget` | 1,000,000 | Total branch-and-bound work budget | `--nodes` |
236
+ | `time_limit_s` | 60.0 | Wall-clock limit measured from the start of the call | `--timeout` |
237
+ | `fragment_bond_pairs` | 20,000 | Ceiling on compatible bond pairs in the fragment search | `--pairs` |
238
+ | `coarse_fragment_steps` | 100,000 | Work cap for the element-independent fragment pass | Python only |
239
+
240
+ Work budgets make the stopping point reproducible, provided the wall-clock limit does
241
+ not intervene. Clock-limited results depend on machine speed and load. The time limit is
242
+ not a hard process deadline: parsing, stereo perception, and result assembly are not
243
+ interrupted. The optional global check described below has its own additional budget.
244
+
245
+ Reaching the coarse-pass cap is part of the normal method and does not set `timed_out`;
246
+ inspect `metadata["fragment_search"]["coarse_capped"]`. The bond-pair ceiling protects
247
+ against large search graphs; increase it if `stopped_by` includes `pairs`.
248
+
249
+ `Settings` also exposes `max_fragments`, `k_seeds`, and `max_alternatives` for advanced
250
+ control of candidate storage and refinement. Restricting seeds or truncating candidates
251
+ can affect mapping quality and consistency under input reversal.
252
+
253
+ ## Optimality and limitations
254
+
255
+ **A completed search is not a proof of the globally best mapping.** AtomMapper starts
256
+ from shared connected fragments, trims them to the constraints, and grows mappings around
257
+ the remaining pieces using branch-and-bound. Each starting piece is held fixed, so the
258
+ usual result is `metadata["optimality"] == "optimal_given_seed"`.
259
+
260
+ The seeds can miss a better mapping, sometimes by a large margin. For example,
261
+ `NC1Cc2ccccc2CCC1=O` to `N[C@H]1CCc2ccccc2C[C@@H]1O` with fixed elements gives a change
262
+ size of 21, although a size of 8 is possible. Extra seeds address common stereo-related
263
+ failures, but do not make the search globally exact. Increasing budgets alone may not
264
+ fix a poor choice of seeds.
265
+
266
+ `Settings(global_budget_s=...)` enables an optional exact lower-bound calculation after
267
+ the search, using unconstrained graph edit distance. If it finishes and matches the
268
+ mapping cost, `optimality` becomes `optimal`. Otherwise, it does not establish optimality.
269
+ This check can be expensive and is intended for small molecules and validation.
270
+
271
+ ## Development
272
+
273
+ Building from source requires Python 3.11+ and Rust:
274
+
275
+ ```bash
276
+ git clone https://github.com/craabreu/atommapper.git
277
+ cd atommapper
278
+ python -m venv .venv
279
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
280
+ python -m pip install -e ".[test,dev]"
281
+
282
+ make check # lint, types, Rust checks and tests, rebuild, Python tests
283
+ make format # format Python and Rust sources
284
+ ```
285
+
286
+ The `make` commands require Make. To run only the Python tests after installation, use
287
+ `python -m pytest -q`. Benchmark dependencies and reproduction commands are documented
288
+ [separately](https://github.com/craabreu/atommapper/blob/main/benchmarks/README.md#reproducing-the-benchmarks).
289
+
290
+ Please report bugs with a minimal pair of input molecules, the mapping options, and
291
+ `result.metadata["versions"]` on the
292
+ [issue tracker](https://github.com/craabreu/atommapper/issues).
293
+
294
+ ## License
295
+
296
+ AtomMapper is released under the [MIT license](https://github.com/craabreu/atommapper/blob/main/LICENSE).