orthonym.namer#

Note

Internal API. Names and behaviour may change between releases.

Main IUPAC nomenclature generator.

Architecture:

SMILES → Perception → Classification → Assembly → IUPAC Name

This is the inverse of OPSIN’s pipeline:

OPSIN: Name → Tokenize → Parse → Build Structure Orthonym: Structure → Perceive → Classify → Assemble Name

orthonym.namer.classify_compound_class(mol, canonical_smiles)#

Classify molecule into compound class for pre-routing.

Returns class label or None for general routing. Classification order per:

steroid -> alkaloid -> terpene -> peptide -> amino_acid -> carbohydrate -> general

Parameters:
  • mol – RDKit Mol object.

  • canonical_smiles (str) – Canonical SMILES string.

Returns:

One of ‘steroid’, ‘alkaloid’, ‘terpene’, ‘carbohydrate’, or None.

Return type:

str | None

class orthonym.namer.MolecularFeatures(mol, smiles='', canonical_smiles='', functional_groups=<factory>, principal_group=None, principal_group_atoms=<factory>, principal_chain=<factory>, atom_to_locant=<factory>, substituents=<factory>, ring_systems=<factory>, all_ring_atoms=<factory>, is_cyclic=False, is_aromatic=False, ring_type=None, principal_ring=None, senior_ring_system=None, oriented_ring=None, ring_substituents=<factory>, ring_double_bonds=<factory>, ring_double_bond_locants=<factory>, ring_assembly_info=None, is_benzene=False, benzene_ring=None, benzene_substituents=<factory>, polycyclic_name=None, polycyclic_substituents=<factory>, heterocycle_info=None, oriented_heterocycle=None, heterocycle_atom_to_locant=None, heterocycle_substituents=<factory>, stereocenters=<factory>, double_bond_stereo=<factory>, double_bonds=<factory>, triple_bonds=<factory>, is_polyfunctional=False, non_principal_groups=<factory>, ester_match=None, amide_type=None, n_substituents=<factory>, ring_substituents_as_groups=<factory>, chain_is_parent=False, species_type='neutral', ion_sites=<factory>, radical_sites=<factory>, total_charge=0, parent_selection_result=None)#

Bases: object

Container for perceived molecular features.

mol: Any#
smiles: str = ''#
canonical_smiles: str = ''#
functional_groups: Dict[str, List[tuple]]#
principal_group: str | None = None#
principal_group_atoms: List[tuple]#
principal_chain: List[int]#
atom_to_locant: Dict[int, int]#
substituents: Dict[int, List[List[int]]]#
ring_systems: List[set]#
all_ring_atoms: frozenset#
is_cyclic: bool = False#
is_aromatic: bool = False#
ring_type: str | None = None#
principal_ring: tuple | None = None#
senior_ring_system: tuple | None = None#
oriented_ring: List[int] | None = None#
ring_substituents: Dict[int, List[List[int]]]#
ring_double_bonds: List[tuple]#
ring_double_bond_locants: List[int]#
ring_assembly_info: Dict | None = None#
is_benzene: bool = False#
benzene_ring: tuple | None = None#
benzene_substituents: Dict[int, List[Dict]]#
polycyclic_name: str | None = None#
polycyclic_substituents: Dict[int, List[Dict]]#
heterocycle_info: Dict | None = None#
oriented_heterocycle: List[int] | None = None#
heterocycle_atom_to_locant: Dict[int, int] | None = None#
heterocycle_substituents: Dict[int, List[Dict]]#
stereocenters: List[dict]#
double_bond_stereo: List[dict]#
double_bonds: List[tuple]#
triple_bonds: List[tuple]#
is_polyfunctional: bool = False#
non_principal_groups: Dict[str, List[tuple]]#
ester_match: tuple | None = None#
amide_type: str | None = None#
n_substituents: List[Dict]#
ring_substituents_as_groups: List[tuple]#
chain_is_parent: bool = False#
species_type: str = 'neutral'#
ion_sites: Dict[str, List[Dict]]#
radical_sites: List[Dict]#
total_charge: int = 0#
parent_selection_result: Any | None = None#
orthonym.namer.compute_features(mol, smiles=None)#

a phase: thin module-level wrapper around Orthonym._perceive.

Provides a public-API perception entry for tests and downstream callers. Mirrors what name_compound does internally before naming.

Parameters:
  • mol – RDKit Mol object.

  • smiles (str | None) – Optional input SMILES; if None, derived via Chem.MolToSmiles(mol).

Returns:

MolecularFeatures populated by Orthonym._perceive.

Return type:

MolecularFeatures

Source: a phase Plan 02 fix (public-API perception entry).

orthonym.namer.BINDING_PROOF_MODES = ('off', 'audit', 'enforce')#

the accepted values of the binding-proof flag.

orthonym.namer.validate_binding_proof(value)#

Single source of truth for the binding-proof mode check.

Shared by Orthonym.__init__ and every surface that accepts the flag (notably the CLI’s --batch path, which builds its namers lazily inside a per-row except Exception and would otherwise degrade a typo into a row-level “ERROR:” line). Validate eagerly and identically everywhere: a misspelled mode that silently degraded to “off” would present as a clean run with the proof never executing – the one failure mode an audit flag must not have.

class orthonym.namer.Orthonym(style='pin', *, _disable_grammar_validation=False, _disable_opsin_validity_gate=False, enable_triviality_controller=False, enable_group_splitting=False, trivial_fallback=False, general_fallback=False, general_fallback_unverified=False, allow_aromatic_general=False, full_coverage=False, _principal_group_override=None, _forced_parent_rank=0, _seed_excluded_dispatch_classes=frozenset({}), binding_proof='off')#

Bases: object

The naming engine, with every option.

Build one instance and name as many molecules with it as you like; the options apply to every call.:func:name_compound builds a fresh instance for each call.

Creating an instance checks that the OPSIN and centres jars are present and stops with an error if they are not (run orthonym --fetch-jars). Set ORTHONYM_ALLOW_REDUCED=1 to name without them, with no OPSIN check.

Parameters:
  • style ({"pin", "general", "cas"}, default "pin") – Naming style, as for:func:name_compound.

  • enable_triviality_controller (bool) – As for:func:name_compound. All default to False.

  • enable_group_splitting (bool) – As for:func:name_compound. All default to False.

  • trivial_fallback (bool) – As for:func:name_compound. All default to False.

  • general_fallback (bool) – The switches behind the command line’s --emit-tier. All default to False, which is the default tier. valid sets general_fallback; complete adds allow_aromatic_general; best-effort adds general_fallback_unverified; full-coverage adds full_coverage.

  • general_fallback_unverified (bool) – The switches behind the command line’s --emit-tier. All default to False, which is the default tier. valid sets general_fallback; complete adds allow_aromatic_general; best-effort adds general_fallback_unverified; full-coverage adds full_coverage.

  • allow_aromatic_general (bool) – The switches behind the command line’s --emit-tier. All default to False, which is the default tier. valid sets general_fallback; complete adds allow_aromatic_general; best-effort adds general_fallback_unverified; full-coverage adds full_coverage.

  • full_coverage (bool) – The switches behind the command line’s --emit-tier. All default to False, which is the default tier. valid sets general_fallback; complete adds allow_aromatic_general; best-effort adds general_fallback_unverified; full-coverage adds full_coverage.

  • binding_proof ({"off", "audit", "enforce"}, default "off") – As for:func:name_compound.

Notes

The parameters whose names start with an underscore are for the engine’s own use and tests; leave them at their defaults.

Examples

>>> from orthonym import Orthonym
>>> namer = Orthonym
>>> namer.name("CCO")
'ethanol'
>>> namer.name("CC(=O)O")
'acetic acid'
get_dispatch_stats()#

Return how often each compound-class route was taken by this instance.

The engine tries compound classes in a fixed order (salts, ions, carbohydrates, natural products, the general rules and more) and counts which class named each molecule.

Returns:

dict – Compound class to count. The keys are members of orthonym.routing.StoutClass.

Return type:

Dict[Any, int]

reset_dispatch_stats()#

Set the route counters back to zero.

Resets this instance’s class counters and the finer counters of get_inner_dispatch_stats(). The finer counters are shared by every instance in the process, so this resets them for all instances.

get_inner_dispatch_stats()#

Return how often each handler inside the general class was used.

Within the general compound class, a second step picks one of several handlers (acids, esters, amines and so on). These counters are shared by every instance in the process;:meth:reset_dispatch_stats clears them.

Returns:

dict of str to int – Handler id to count; empty before the first molecule.

Return type:

Dict[str, int]

name_with_tree(smiles)#

Name one molecule and return the parts of the name.

Parameters:

smiles (str) – The structure, as a SMILES string.

Returns:

NamingResult – name is the same string:meth:name returns; tree is the NameTreeNode of its parts (a single coarse node when the part of the engine that built the name records no finer structure); atom_to_locant_hint maps atom indices to locants where one was recorded, else None.

Raises:

ValueError – If RDKit cannot read the SMILES.

Examples

>>> from orthonym import Orthonym
>>> Orthonym.name_with_tree("OC1CCCCC1").name
'cyclohexanol'
get_validation_stats()#

Return how often the OPSIN grammar pre-check passed or repaired a name.

The engine checks a candidate against OPSIN’s grammar before the full round trip, and can fix brackets, stereodescriptors or hyphens. The counters belong to this instance and start at zero.

Returns:

dict of str to int – One counter per outcome, for example validate_passed and repair_succeeded_bracket.

Return type:

Dict[str, int]

name(smiles, *, raise_on_limit=False)#

Name one molecule with this instance’s options.

Parameters:
  • smiles (str) – The structure, as a SMILES string.

  • raise_on_limit (bool, default False) – Raise:class:OrthonymLimitError for a structure the engine cannot handle, instead of returning a label.

Returns:

str – The name, or a label that says why no name was given (see orthonym.errors.is_failure_name()).

Raises:
  • ValueError – If RDKit cannot read the SMILES.

  • OrthonymLimitError – If raise_on_limit is true and the structure is out of scope. For a ring system the engine cannot name yet the code is UNSUPPORTED_RING_SYSTEM; when that happens inside a part of the molecule, the code reported can be the more general UNNAMEABLE.

Return type:

str

Examples

>>> from orthonym import Orthonym
>>> Orthonym.name("C/C=C/C")
'(2E)-but-2-ene'
name_tiered(smiles)#

Name one molecule and say how the name was made and checked.

This is the row the command line prints with --provenance.

Parameters:

smiles (str) – The structure, as a SMILES string.

Returns:

dict –

name

The name, or a label when there is none.

tier

How the name was built: pin_verified (the strict path for the Preferred IUPAC Name built it, certified it and OPSIN read it back), pin_unverified (a name in preferred-name form that OPSIN read back, but whose preferred status is not certified: a producer outside the strict path built it or a part of it), systematic_verified (a checked systematic name that is not the preferred name, from the general engine, a table of retained names, or the strict path when the name contains a part the engine records as not the preferred form), best_effort (the last-resort producers, or a name whose own string no round trip confirmed) or abstain (no name).

is_pin

True only for a certified Preferred IUPAC Name.

source

Which part of the engine produced the name, for example pin_path, general_engine, trivial_retained or abstain.

opsin

What the OPSIN check found: verified, verified_constitution_only, unverified or n/a.

gates_passed

The checks this name passed, for example self_consistency (OPSIN read the name back to your structure) and atom_coverage.

gate_outcome

What the final OPSIN check did for this name, for example self_consistency_verified, suppressed or not_run, or carveout:<class> for a class OPSIN cannot read.

formula

The molecular formula, given when there is no name.

limit_code

The reason code when there is no name, for example UNSUPPORTED_ELEMENT, or NO_VERIFIED_PIN when the default tier built a name that is not a verified PIN (a wider tier returns it).

stereo_unexpressed

True when a stereocentre of the input is not stated in the name.

suffix_free_prefix_name

True when the name states the principal characteristic group as a prefix with no suffix.

prefix_order_fallback

True when the name cites its substituent prefixes out of the alphanumerical order because the round trip of the ordered spelling fails at the stereo layer only (a stereocentre read differently by the SMILES hand-off, not by the name); such a name is best_effort, never a PIN.

verified

opsin (OPSIN read the whole name back to the same molecule), opsin_constitution (read back with the same constitution; the stereodescriptors were not confirmed by OPSIN), identity (a name from an exact-match list: a metal-complex name found by the input’s exact InChIKey, or a natural-product parent name found by its exact structure; OPSIN cannot read these names) or unverified (no read-back recorded).

Return type:

dict

Examples

>>> from orthonym import Orthonym
>>> row = Orthonym.name_tiered("Cn1cnc2c1c(=O)n(C)c(=O)n2C")
>>> row["name"], row["tier"], row["verified"]
('1,3,7-trimethyl-3,7-dihydro-1H-purine-2,6-dione', 'pin_verified', 'opsin')
name_with_confidence(smiles)#

Name one molecule and return a coverage score with it.

Returns:

dict – name (the name), confidence (a score from 0 to 1, or None when no measurement was taken), verification, factors (the parts of the score), handler (the part of the engine that built the name), and further keys for the atom-to-locant map and the reason for a decline (limit, abstention).

Raises:

ValueError – If RDKit cannot read the SMILES.

Return type:

dict

Examples

>>> from orthonym import Orthonym
>>> Orthonym.name_with_confidence("CCO")["name"]
'ethanol'
orthonym.namer.name_with_tree(smiles, style='pin')#

Name one molecule and return the parts of the name.

A shortcut for Orthonym(style=style).name_with_tree(smiles).

Parameters:
  • smiles (str) – The structure, as a SMILES string.

  • style ({"pin", "general", "cas"}, default "pin") – Naming style, as for:func:name_compound.

Returns:

NamingResult – The name (the same string:func:name_compound returns), the tree of its parts as a:class:NameTreeNode, and a map from atom index to locant where one was recorded.

Raises:

ValueError – If RDKit cannot read the SMILES.

Examples

>>> from orthonym import name_with_tree
>>> result = name_with_tree("OC1CCCCC1")
>>> result.name
'cyclohexanol'
>>> result.tree.parent_stem
'cyclohex'
>>> result.tree.suffix
'ol'
orthonym.namer.name_compound(smiles, style='pin', include_confidence=False, *, enable_triviality_controller=False, enable_group_splitting=False, trivial_fallback=False, general_fallback=None, general_fallback_unverified=None, allow_aromatic_general=None, full_coverage=None, raise_on_limit=False, binding_proof='off')#

Name one molecule.

Reads a structure written as SMILES and returns its IUPAC name as a string. At the default settings a name is returned only when the strict path for the Preferred IUPAC Name built it and verified it, or when it is one of the default tier’s exceptions (the exact-match list names, the few name formats OPSIN cannot read, a PIN whose stereodescriptors OPSIN cannot read); otherwise, and where no name passes, it is a label such as 'unknown organic compound' or 'inorganic compound (not supported)'. The wider tiers (general_fallback and the options below) also return names that are not the preferred name. Use orthonym.errors.is_failure_name() to tell a label from a name, and Orthonym.name_tiered() to learn which tier a name earned.

Parameters:
  • smiles (str) – The structure, as a SMILES string.

  • style ({"pin", "general", "cas"}, default "pin") – Naming style. "pin" aims at the Preferred IUPAC Name. "general" allows a few general IUPAC forms where the recommendations offer one (for example some adduct names and axial stereodescriptors). "cas" is accepted and at present gives the same names as "pin".

  • include_confidence (bool, default False) – Return a dictionary instead of a string. Its "name" key holds the name, "handler" the part of the engine that built it, and "confidence" and "factors" a coverage score and its parts. "confidence" is None when no measurement was taken.

  • enable_triviality_controller (bool, default False) – Where the recommendations prefer a retained parent name to the systematic one, use the retained name. Each change is checked by an OPSIN round trip. The environment setting ORTHONYM_ENABLE_TRIVIALITY_CONTROLLER=1 turns this on as well.

  • enable_group_splitting (bool, default False) – When an ester or thioester group inside a larger molecule has no prefix form, write it as its parts (oxo plus ethoxy, for example) instead of giving up. Each split name must pass an OPSIN round trip. The environment setting ORTHONYM_ENABLE_GROUP_SPLITTING=1 turns this on as well.

  • trivial_fallback (bool, default False) – When no preferred name can be built, also allow a retained trivial name that is not a preferred name. A molecule whose preferred name can be built keeps it. Turns on enable_triviality_controller.

  • general_fallback (bool or None, default None) – When the strict path declines, try the general naming engine (the valid tier of the command line). Its names must pass an atom-coverage certificate and a full-InChIKey round trip. None means “off” for a call you make; the engine uses it to pass the setting on when it names parts of a molecule.

  • general_fallback_unverified (bool or None, default None) – Also switch on the best-effort tier: the last-resort producers, von Baeyer and spiro names for ring systems of up to 100 skeletal atoms and 11 rings (the other tiers build these names for ring systems of up to 40 skeletal atoms and 8 rings), and adducts with a one-atom ion. Their names still have to pass the full-InChIKey round trip. None as for general_fallback.

  • allow_aromatic_general (bool or None, default None) – Let the general engine also name aromatic and heterocyclic ring systems (the complete tier). None as for general_fallback.

  • full_coverage (bool or None, default None) – Also try the coordination-name builder for metal tetrapyrrole and corrin complexes (the full-coverage tier). It builds a name or declines. None as for general_fallback.

  • raise_on_limit (bool, default False) – Raise:class:OrthonymLimitError for a structure the engine cannot handle, instead of returning a label.

  • binding_proof ({"off", "audit", "enforce"}, default "off") – An extra check that every part of a general-engine name still maps onto the atoms it names in the final string. "audit" records the result and never changes the name; "enforce" also declines when the check fails.

Returns:

str or dict – The name, or a label that says why no name was given. A dictionary when include_confidence is true.

Raises:
  • ValueError – If RDKit cannot read the SMILES, or binding_proof is not one of the three values.

  • OrthonymLimitError – If raise_on_limit is true and the structure is out of scope.

Examples

>>> from orthonym import name_compound
>>> name_compound("CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O")
'(2R)-2-[4-(2-methylpropyl)phenyl]propanoic acid'
>>> name_compound("O=[U](=O)=O")
'inorganic compound (not supported)'
orthonym.namer.name_pipeline_only(smiles, style='pin')#

Name a molecule using only the systematic pipeline, skipping decomposition.

This provides the non-decomposition name without consuming any depth budget on decomposition probes. Used by the decomposition engine to compare its result against what the systematic pipeline would produce.

Returns:

IUPAC name string, or None if naming fails.

orthonym.namer.classify_limit(smiles)#

Say whether a structure is out of scope, without raising.

A wildcard atom (*) is refused at once. Any other structure is named with the default settings; if that gives a label instead of a name, the reason is returned.

Parameters:

smiles (str) – The structure, as a SMILES string.

Returns:

OrthonymLimitError or None – The reason, with its code (for example UNSUPPORTED_ELEMENT, WILDCARD_ATOMS, or NO_VERIFIED_PIN when the default settings built a name that is not a verified preferred IUPAC name) and message. None when the structure gets a name, and also when RDKit cannot read the SMILES at all (that is a reading error, not a scope limit).

Return type:

OrthonymLimitError | None

Examples

>>> from orthonym import classify_limit
>>> classify_limit("O=[U](=O)=O").code
'UNSUPPORTED_ELEMENT'
>>> classify_limit("CC*").code
'WILDCARD_ATOMS'
>>> classify_limit("CCO") is None
True