Representation

Turning molecules into numbers. Fingerprints, descriptor blocks and learned embeddings, all as scikit-learn transformers accepting Iterable[rdkit.Chem.Mol] and returning a NumPy array.

Choosing a representation matters more than choosing a model. A random forest on good features beats a tuned neural network on bad ones, and no amount of hyperparameter search recovers information the representation threw away.

Fingerprints

>>> from qsarkit.representation import MorganFingerprint
>>> X = MorganFingerprint(radius=2, n_bits=1024).transform(demo_mols)
>>> X.shape
(24, 1024)

Morgan (ECFP) fingerprints are the default for good reason: they encode circular atom environments, are cheap, and work well with tree ensembles and Tanimoto-kernel methods. The radius is the substantive choice — radius 2 (ECFP4) captures functional groups, radius 3 (ECFP6) captures larger motifs at the cost of sparsity.

Fingerprints are sparse. Most bits never fire on a small dataset:

>>> int((X.sum(axis=0) > 0).sum())
133

The other families answer different questions:

>>> from qsarkit.representation import (
...     AtomPairFingerprint, MACCSKeysFingerprint, RDKitFingerprint)
>>> MACCSKeysFingerprint().transform(demo_mols).shape
(24, 167)
>>> RDKitFingerprint(n_bits=512).transform(demo_mols).shape
(24, 512)
>>> AtomPairFingerprint(n_bits=512).transform(demo_mols).shape
(24, 512)

MACCS keys are 166 hand-curated substructure questions — interpretable and fixed-length, but far less expressive than a hashed fingerprint. Atom pairs and topological torsions are count vectors by design, encoding how often a feature occurs rather than merely whether it does.

Combining them needs no new machinery:

>>> from qsarkit.representation import FingerprintCombiner
>>> combined = FingerprintCombiner([
...     ("morgan", MorganFingerprint(n_bits=64)),
...     ("maccs", MACCSKeysFingerprint()),
... ])
>>> combined.transform(demo_mols).shape
(24, 231)

Descriptors

Where fingerprints answer “what substructures are present”, descriptors answer “what is this molecule like”.

>>> from qsarkit.representation import PhysicochemicalDescriptors
>>> block = PhysicochemicalDescriptors()
>>> list(block.get_feature_names_out()[:4])
['MolWt', 'MolLogP', 'TPSA', 'NumHDonors']
>>> block.transform(demo_mols).shape
(24, 9)
>>> from qsarkit.representation import LipinskiDescriptors, RDKitDescriptors
>>> RDKitDescriptors().transform(demo_mols[:1]).shape
(1, 217)
>>> LipinskiDescriptors().transform(demo_mols).shape
(24, 9)

Warning

Descriptors are continuous and on wildly different scales — molecular weight in the hundreds, logP in single digits. Any distance-based or regularized model needs them scaled first (see DescriptorScaler). Fingerprints, being binary, do not.

Learned embeddings

Mol2VecTransformer and ChemBERTaTransformer need the embeddings and nlp extras respectively. They are lazily imported, so import qsarkit stays cheap:

from qsarkit.representation import ChemBERTaTransformer

X = ChemBERTaTransformer().transform(mols)     # needs qsarkit-learn[nlp]

API

Molecular representations: fingerprints, descriptors and embeddings.

Every transformer accepts Iterable[rdkit.Chem.Mol], returns a NumPy array, and exposes get_feature_names_out().

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation import MorganFingerprint
>>> X = MorganFingerprint(n_bits=256).transform([Chem.MolFromSmiles("CCO")])
>>> X.shape
(1, 256)

References

class qsarkit.representation.BaseFingerprintTransformer[source]

Bases: MoleculeTransformer

Abstract base for dense, fixed-width molecular fingerprints.

Notes

None entries in the input (molecules that failed an earlier parsing or standardization step) are encoded as an all-zero row so that the output stays positionally aligned with the input, mirroring the convention used by qsarkit.chemistry.MolecularStandardizer. Output arrays are always float64 so that fingerprints compose directly with downstream scikit-learn estimators/scalers without an implicit cast; the intermediate RDKit bit/count vectors are generated in their natural uint8/uint32 dtype for efficiency and cast on assignment into the output matrix.

References

abstract property n_features_out: int

Width of the produced feature matrix.

get_feature_names_out(input_features=None)[source]

Return n_features_out bit/count names.

Parameters:

input_features (Optional[Sequence[str]]) – Ignored; present for scikit-learn API compatibility.

Returns:

Array of str names, one per output column.

Return type:

ndarray[tuple[Any, ...], dtype[object_]]

Examples

>>> from qsarkit.representation.fingerprints import MACCSKeysFingerprint
>>> len(MACCSKeysFingerprint().get_feature_names_out())
167
set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

qsarkit.representation.fold_on_bits(on_bits, n_bits)[source]

Fold a sparse list of set bit indices into a dense n_bits vector.

Parameters:
  • on_bits (Sequence[int]) – Indices of the set bits in a (possibly very large) sparse bit vector.

  • n_bits (int) – Width of the folded output.

Returns:

float64 array of length n_bits holding 0/1 values.

Return type:

ndarray[tuple[Any, ...], dtype[double]]

Notes

Modulo folding is the standard RDKit approach for reducing sparse fingerprints (e.g. the 39 972-bit Gobbi 2D pharmacophore keys) to a machine-learning friendly width; it trades bit collisions for a fixed, dense representation.

Examples

Bits 0, 5 and 10 fold to 0, 1 and 2 modulo 4:

>>> fold_on_bits([0, 5, 10], 4).tolist()
[1.0, 1.0, 1.0, 0.0]

Collisions are silent, which is the cost of folding – bits 1 and 5 land on the same output position:

>>> fold_on_bits([1, 5], 4).tolist()
[0.0, 1.0, 0.0, 0.0]

References

class qsarkit.representation.MorganFingerprint(n_bits=2048, radius=2, use_counts=False, use_features=False, use_chirality=False, use_bond_types=True)[source]

Bases: BaseFingerprintTransformer

Morgan (circular) fingerprints, i.e. ECFP and FCFP.

Iteratively hashes the circular atom environment of every atom up to radius bonds and folds the resulting identifiers into n_bits. With use_features=False the atom invariants are connectivity based (ECFP flavour); with use_features=True they are the Gobbi-style pharmacophoric feature invariants (FCFP flavour). The ECFP diameter naming convention corresponds to 2 * radius (radius=2 -> ECFP4).

Parameters:
  • n_bits (int) – Width of the folded fingerprint.

  • radius (int) – Maximum circular environment radius, in bonds.

  • use_counts (bool) – If True return per-bit occurrence counts (uint32) instead of a binary vector (uint8).

  • use_features (bool) – Use pharmacophoric (FCFP) rather than connectivity (ECFP) atom invariants.

  • use_chirality (bool) – Include chiral tags in the atom invariants.

  • use_bond_types (bool) – Include bond orders when hashing environments.

Variables:

n_features_out (int) – Equal to n_bits.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.fingerprints import MorganFingerprint
>>> mols = [Chem.MolFromSmiles("CCO"), Chem.MolFromSmiles("c1ccccc1")]
>>> X = MorganFingerprint(n_bits=64, radius=2).fit_transform(mols)
>>> X.shape
(2, 64)

References

property n_features_out: int

Width of the produced feature matrix.

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.FeatureMorganFingerprint(n_bits=2048, radius=2, use_counts=False, use_chirality=False, use_bond_types=True)[source]

Bases: MorganFingerprint

FCFP-flavoured Morgan fingerprint (pharmacophoric atom invariants).

Thin convenience subclass of MorganFingerprint with use_features=True; feature types are donor, acceptor, aromatic, halogen, basic and acidic, as defined by the Gobbi & Poppinger pharmacophore typing rules used by RDKit.

Parameters:
  • n_bits (int) – Width of the folded fingerprint.

  • radius (int) – Maximum circular environment radius, in bonds.

  • use_counts (bool) – Return counts rather than bits.

  • use_chirality (bool) – Include chiral tags in the atom invariants.

  • use_bond_types (bool) – Include bond orders when hashing environments.

References

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.RDKitFingerprint(n_bits=2048, min_path=1, max_path=7, n_bits_per_hash=2, use_counts=False, branched_paths=True, use_hs=True)[source]

Bases: BaseFingerprintTransformer

The RDKit topological (Daylight-like) path fingerprint.

Enumerates all linear and branched subgraphs of the molecule with a number of bonds between min_path and max_path, hashes each one and sets n_bits_per_hash bits per subgraph in an n_bits-wide vector. This is RDKit’s default general-purpose substructure fingerprint and is closely related to the classic Daylight fingerprint.

Parameters:
  • n_bits (int) – Width of the folded fingerprint.

  • min_path (int) – Minimum number of bonds in the hashed subgraphs.

  • max_path (int) – Maximum number of bonds in the hashed subgraphs.

  • n_bits_per_hash (int) – Number of bits set per hashed subgraph.

  • use_counts (bool) – Return per-bit occurrence counts instead of a binary vector.

  • branched_paths (bool) – Include branched subgraphs in addition to linear paths.

  • use_hs (bool) – Include information about the number of hydrogens on each atom.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.fingerprints import RDKitFingerprint
>>> RDKitFingerprint(n_bits=128).fit_transform([Chem.MolFromSmiles("CCO")]).shape
(1, 128)

References

property n_features_out: int

Width of the produced feature matrix.

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.PatternFingerprint(n_bits=2048, tautomeric=False)[source]

Bases: BaseFingerprintTransformer

RDKit pattern fingerprint, designed as a substructure-search screen.

The pattern fingerprint enumerates small atom/bond patterns and is built so that fp(query) & fp(target) == fp(query) whenever query is a substructure of target. That screening property makes it a strong similarity descriptor for substructure-driven SAR, at the cost of being much denser than ECFP-type fingerprints.

Parameters:
  • n_bits (int) – Width of the fingerprint.

  • tautomeric (bool) – Use the tautomer-insensitive variant (Chem.PatternFingerprint(..., tautomerFingerprints=True)), which makes the screen invariant to common tautomeric shifts.

Notes

This fingerprint is binary only: RDKit does not expose a count variant, so no use_counts parameter is offered.

References

property n_features_out: int

Width of the produced feature matrix.

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.LayeredFingerprint(n_bits=2048, min_path=1, max_path=7, layer_flags=4294967295, branched_paths=True)[source]

Bases: BaseFingerprintTransformer

RDKit layered fingerprint (substructure fingerprint with atom layers).

Like RDKitFingerprint it hashes subgraphs, but each subgraph is described through several independent “layers” (pure topology, bond order, atom types, ring membership, …), selected by layer_flags. Combining layers yields a fingerprint that degrades gracefully between a pure-topology and a fully atom-typed description.

Parameters:
  • n_bits (int) – Width of the fingerprint.

  • min_path (int) – Minimum number of bonds in the hashed subgraphs.

  • max_path (int) – Maximum number of bonds in the hashed subgraphs.

  • layer_flags (int) – Bitmask selecting which layers contribute (RDKit default: all).

  • branched_paths (bool) – Include branched subgraphs in addition to linear paths.

References

property n_features_out: int

Width of the produced feature matrix.

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.AtomPairFingerprint(n_bits=2048, min_distance=1, max_distance=30, use_counts=True, use_chirality=False)[source]

Bases: BaseFingerprintTransformer

Carhart atom-pair fingerprint.

Each feature is the triplet (atom type i, topological distance, atom type j) for every pair of atoms whose shortest-path distance lies between min_distance and max_distance. Atom types encode element, number of heavy-atom neighbours and number of pi electrons. The triplets are hashed into n_bits.

Parameters:
  • n_bits (int) – Width of the folded fingerprint.

  • min_distance (int) – Minimum topological (bond) distance between paired atoms.

  • max_distance (int) – Maximum topological (bond) distance between paired atoms.

  • use_counts (bool) – Return per-bit occurrence counts. Atom pairs were defined as a counted descriptor in the original publication, so counts are the default here (unlike the other fingerprints in this module).

  • use_chirality (bool) – Include chiral tags in the atom types.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.fingerprints import AtomPairFingerprint
>>> AtomPairFingerprint(n_bits=64).fit_transform([Chem.MolFromSmiles("CCO")]).shape
(1, 64)

References

property n_features_out: int

Width of the produced feature matrix.

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.TopologicalTorsionFingerprint(n_bits=2048, torsion_size=4, use_counts=True, use_chirality=False)[source]

Bases: BaseFingerprintTransformer

Nilakantan topological-torsion fingerprint.

Enumerates every linear path of torsion_size consecutively bonded non-hydrogen atoms (four by default, i.e. a torsion) and hashes the ordered tuple of their atom types into n_bits. Torsions complement atom pairs by encoding short-range, shape-relevant connectivity.

Parameters:
  • n_bits (int) – Width of the folded fingerprint.

  • torsion_size (int) – Number of atoms in each hashed path.

  • use_counts (bool) – Return per-bit occurrence counts (the original formulation is a counted descriptor).

  • use_chirality (bool) – Include chiral tags in the atom types.

References

property n_features_out: int

Width of the produced feature matrix.

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.MACCSKeysFingerprint(drop_unused_bit=False)[source]

Bases: BaseFingerprintTransformer

166 public MACCS structural keys (RDKit implementation, 167 bits).

Each bit is a hand-curated SMARTS substructure query (“has a carbonyl”, “has 4 nitrogens”, …). Unlike the hashed fingerprints in this module MACCS keys are directly interpretable, which makes them useful for explainable QSAR and for coarse similarity screening.

Parameters:

drop_unused_bit (bool) – RDKit returns 167 bits, index 0 being an always-off placeholder so that key k lands at index k. Set to True to drop it and return exactly the 166 defined keys.

Notes

RDKit implements the 166 public MACCS key definitions; a handful of keys that require proprietary MDL features are approximated, as documented in rdkit.Chem.MACCSkeys. The fingerprint has no n_bits/radius/use_counts parameters because the key set is fixed and binary by definition.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.fingerprints import MACCSKeysFingerprint
>>> MACCSKeysFingerprint().fit_transform([Chem.MolFromSmiles("CCO")]).shape
(1, 167)

References

property n_features_out: int

Width of the produced feature matrix.

get_feature_names_out(input_features=None)[source]

Return n_features_out bit/count names.

Parameters:

input_features (Optional[Sequence[str]]) – Ignored; present for scikit-learn API compatibility.

Returns:

Array of str names, one per output column.

Return type:

ndarray

Examples

>>> from qsarkit.representation.fingerprints import MACCSKeysFingerprint
>>> len(MACCSKeysFingerprint().get_feature_names_out())
167
set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.AvalonFingerprint(n_bits=512, use_counts=False, is_query=False, bit_flags=15761407)[source]

Bases: BaseFingerprintTransformer

Avalon substructure fingerprint.

The Avalon cheminformatics toolkit enumerates a fixed, hand-designed set of feature classes (paths, rings, atom pairs at short distances, augmented atoms, …) and hashes them into a folded bit vector. In the original benchmark it matched or outperformed contemporary path- and circular-based fingerprints on similarity searching.

Parameters:
  • n_bits (int) – Width of the folded fingerprint. 512 is the size used in the original publication and the RDKit default.

  • use_counts (bool) – Return per-feature occurrence counts (pyAvalonTools.GetAvalonCountFP) instead of a binary vector.

  • is_query (bool) – Generate the query flavour of the fingerprint, used when the molecule is a substructure query rather than a full structure.

  • bit_flags (int) – Feature-class bitmask; the default is Avalon’s avalonSSSBits similarity setting used by RDKit.

Raises:

OptionalDependencyError – If the RDKit build does not include the Avalon toolkit bindings (rdkit.Avalon.pyAvalonTools). Conda/PyPI RDKit wheels ship it, but minimal or source builds may omit it.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.fingerprints import AvalonFingerprint
>>> AvalonFingerprint(n_bits=256).fit_transform([Chem.MolFromSmiles("CCO")]).shape
(1, 256)

References

DEFAULT_BIT_FLAGS

RDKit’s default Avalon similarity bit flags (avalonSimilarityBits).

property n_features_out: int

Width of the produced feature matrix.

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.PharmacophoreFingerprint(n_bits=2048)[source]

Bases: BaseFingerprintTransformer

Gobbi 2D pharmacophore fingerprint.

Atoms are typed into pharmacophoric classes (hydrogen-bond donor, acceptor, positive/negative ionizable, aromatic, lipophilic) using the Gobbi & Poppinger SMARTS definitions shipped with RDKit (rdkit.Chem.Pharm2D.Gobbi_Pharm2D). Every 2- and 3-point combination of typed atoms, binned by topological distance, becomes one bit of a very sparse 39 972-bit vector.

Parameters:

n_bits (Optional[int]) – If given, the sparse key space is modulo-folded onto n_bits columns, which keeps the output dense and machine-learning ready. Pass None to return the full, unfolded 39 972-bit vector.

Notes

Deviation from the original specification: the Gobbi signature is defined over 39 972 keys, which is impractical as a dense design matrix for typical QSAR datasets. By default this transformer therefore folds the set bits modulo n_bits (the standard RDKit folding strategy), accepting bit collisions in exchange for a compact representation. Set n_bits=None to recover the exact, unfolded key vector.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.fingerprints import PharmacophoreFingerprint
>>> fp = PharmacophoreFingerprint(n_bits=256)
>>> fp.fit_transform([Chem.MolFromSmiles("CC(=O)Oc1ccccc1C(=O)O")]).shape
(1, 256)

References

property n_features_out: int

Width of the produced feature matrix.

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.MHFPFingerprint(n_permutations=2048, radius=3, min_radius=1, n_bits=2048, fold=False, rings=True, isomeric=False, kekulize=True, seed=42)[source]

Bases: BaseFingerprintTransformer

MHFP6 - MinHashed fingerprint of circular substructure SMILES.

The molecule is decomposed into the set of canonical SMILES of all circular substructures (“shingles”) up to radius bonds; that set is then compressed with MinHash into n_permutations 32-bit hash values. The MinHash vector approximates the Jaccard distance between shingle sets, which makes MHFP6 a strong similarity and virtual-screening descriptor for large, diverse libraries.

Two output modes are available:

fold=False (default)

Return the raw uint32 MinHash vector of length n_permutations. This is the representation used for MinHash-LSH nearest-neighbour search.

fold=True

Return the folded binary SECFP variant of width n_bits, which is directly usable as a design matrix for scikit-learn models.

Parameters:
  • n_permutations (int) – Number of MinHash permutations (length of the unfolded vector).

  • radius (int) – Maximum circular substructure radius (“6” in MHFP6 is the diameter).

  • min_radius (int) – Minimum circular substructure radius.

  • n_bits (int) – Width of the folded binary output when fold=True.

  • fold (bool) – Emit the folded binary SECFP vector instead of the MinHash vector.

  • rings (bool) – Include whole-ring SMILES as additional shingles (folded mode).

  • isomeric (bool) – Keep stereochemistry in the shingle SMILES.

  • kekulize (bool) – Kekulize substructures before writing their SMILES.

  • seed (int) – Seed of the MinHash permutation set; fixing it makes the transformer deterministic and comparable across runs.

Notes

use_counts is not offered: a MinHash sketch is a set summary and has no meaningful multiplicity.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.fingerprints import MHFPFingerprint
>>> fp = MHFPFingerprint(n_permutations=64)
>>> fp.fit_transform([Chem.MolFromSmiles("CCO")]).shape
(1, 64)

References

property n_features_out: int

Width of the produced feature matrix.

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.MAP4Fingerprint(n_permutations=2048, radius=2, max_distance=None, n_bits=2048, fold=False, isomeric=False, seed=42)[source]

Bases: BaseFingerprintTransformer

MAP4 - MinHashed atom-pair fingerprint of radius 2.

MAP4 merges the two ideas behind AtomPairFingerprint and MHFPFingerprint: for every pair of atoms (i, j) and every radius r <= radius, the canonical SMILES of the circular substructures around i and j are paired with their topological distance d into a shingle "smiles_a|d|smiles_b" (the two SMILES sorted lexicographically so the shingle is order independent). The resulting shingle set is compressed by MinHash exactly as in MHFP. The authors show MAP4 performs well across both small molecules and peptides/macrocycles, where circular-only fingerprints degrade.

Parameters:
  • n_permutations (int) – Number of MinHash permutations (output width when fold=False).

  • radius (int) – Maximum circular substructure radius around each atom of the pair.

  • max_distance (Optional[int]) – Only pair atoms whose topological distance is at most this value. None (default) uses all pairs, as in the reference implementation.

  • n_bits (int) – Width of the folded binary output when fold=True.

  • fold (bool) – Fold the MinHash vector modulo n_bits into a binary vector.

  • isomeric (bool) – Keep stereochemistry in the shingle SMILES.

  • seed (int) – Seed of the MinHash permutation set.

Notes

Deviation: the reference implementation (map4) is not on PyPI as a maintained wheel, so the shingling step is re-implemented here directly on top of RDKit (FindAtomEnvironmentOfRadiusN + PathToSubmol), and the MinHash step reuses the MHFP encoder from the mhfp package when present or RDKit’s native port otherwise. The shingle grammar follows Capecchi et al. exactly.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.fingerprints import MAP4Fingerprint
>>> MAP4Fingerprint(n_permutations=32).fit_transform(
...     [Chem.MolFromSmiles("CCO")]
... ).shape
(1, 32)

References

property n_features_out: int

Width of the produced feature matrix.

shingles(mol)[source]

Return the MAP4 shingle set of one molecule.

Parameters:

mol (Mol) – Molecule to decompose.

Returns:

Shingles of the form "<smiles_a>|<distance>|<smiles_b>".

Return type:

List[str]

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.FingerprintCombiner(transformers, weights=None)[source]

Bases: MoleculeTransformer

Horizontally concatenate several fingerprint/descriptor transformers.

Many QSAR pipelines combine a circular fingerprint with a structural-key or physicochemical descriptor block (e.g. ECFP4 + MACCS, or ECFP4 + Lipinski descriptors) because the two capture complementary information. FingerprintCombiner fits each member transformer independently on the same molecules and concatenates their outputs column-wise, exposing the combination as a single scikit-learn transformer that fits and transforms in one call.

Parameters:
  • transformers (Sequence[Tuple[str, MoleculeTransformer]]) – Named member transformers. Each must implement fit/transform (or fit_transform) over Iterable[Mol] and return a 2-D numpy.ndarray with a consistent number of rows. Names are used to prefix get_feature_names_out() and must be unique.

  • weights (Optional[Sequence[float]]) – Per-member multiplicative weight applied to that member’s output block before concatenation. Defaults to 1.0 for every member.

Variables:

n_features_out (int) – Total width of the concatenated output, set after fit.

Notes

This mirrors the intent of sklearn.pipeline.FeatureUnion but is specialized to the Iterable[Mol] input contract used throughout qsarkit (FeatureUnion itself works fine with these transformers too; this class exists for a lighter-weight, dependency-free alternative and for symmetry with qsarkit.transform.MoleculeFeatureUnion, which wraps the same pattern for the qsarkit.transform namespace).

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.fingerprints import (
...     FingerprintCombiner, MorganFingerprint, MACCSKeysFingerprint,
... )
>>> combiner = FingerprintCombiner([
...     ("morgan", MorganFingerprint(n_bits=32)),
...     ("maccs", MACCSKeysFingerprint()),
... ])
>>> X = combiner.fit_transform([Chem.MolFromSmiles("CCO")])
>>> X.shape
(1, 199)

References

fit(mols, y=None)[source]

Fit every member transformer on the same molecules.

Parameters:
Returns:

self.

Return type:

FingerprintCombiner

get_feature_names_out(input_features=None)[source]

Return prefixed feature names from every member transformer.

Parameters:

input_features (Optional[Sequence[str]]) – Ignored; present for scikit-learn API compatibility.

Returns:

Array of str names, formatted "<member_name>__<feature>".

Return type:

ndarray[tuple[Any, ...], dtype[object_]]

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.BaseDescriptorTransformer[source]

Bases: MoleculeTransformer

Abstract base for dense, named scalar molecular-descriptor blocks.

Notes

missing_value (a constructor argument on every concrete subclass, following the sklearn convention of storing constructor arguments verbatim) is substituted whenever a descriptor function raises or returns a non-finite value, and for every column of a None input molecule – keeping the output positionally aligned with the input, as elsewhere in qsarkit.representation.

Catching a bare Exception around each descriptor call is a deliberate exception to the “no defensive try/except around internal calls” rule: the functions dispatched here are heterogeneous, third-party (RDKit) callables applied to arbitrary user molecules, and a handful of them (e.g. Ipc on large fused-ring systems, most 3-D descriptors on disconnected inputs) are documented to raise rather than return NaN. This is exactly the kind of untrusted-input boundary the project style guide carves out for explicit error handling.

References

missing_value: float

Value substituted for a descriptor that raised or was non-finite. Every concrete subclass declares this as a constructor argument (default nan) and stores it verbatim, per the sklearn estimator convention; declared here so base-class methods can reference it.

get_feature_names_out(input_features=None)[source]

Return the descriptor names produced by this transformer.

Parameters:

input_features (Optional[Sequence[str]]) – Ignored; present for scikit-learn API compatibility.

Returns:

Array of str names, one per output column.

Return type:

ndarray[tuple[Any, ...], dtype[object_]]

Examples

>>> from qsarkit.representation.descriptors import LipinskiDescriptors
>>> "MolWt" in LipinskiDescriptors().get_feature_names_out()
True
set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.RDKitDescriptors(descriptor_names=None, missing_value=nan)[source]

Bases: BaseDescriptorTransformer

Every descriptor registered in rdkit.Chem.Descriptors._descList.

RDKit registers on the order of 200 2-D/topological/electronic descriptors – molecular weight and LogP, TPSA, connectivity and shape indices (Chi, Kappa), BCUT eigenvalues, VSA bins (PEOE_VSA, SMR_VSA, SlogP_VSA), fragment counts, ring/heteroatom counts, and more – in a single lookup table, Descriptors._descList. This transformer exposes that entire catalogue, or a user-selected subset of it, as one dense, named feature block. A handful of these descriptors (notably Ipc on large fused-ring systems) can raise or overflow to inf/nan on some molecules; both cases are substituted with missing_value.

Parameters:
  • descriptor_names (Optional[Sequence[str]]) – Names of the descriptors to compute (must be keys of rdkit.Chem.Descriptors._descList). None (default) computes every registered descriptor, in the order RDKit registers them.

  • missing_value (float) – Value substituted when a descriptor raises or returns a non-finite value for a given molecule.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.descriptors import RDKitDescriptors
>>> rd = RDKitDescriptors(descriptor_names=["MolWt", "TPSA"])
>>> rd.fit_transform([Chem.MolFromSmiles("CCO")]).shape
(1, 2)
>>> list(rd.get_feature_names_out())
['MolWt', 'TPSA']

References

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.Descriptors3D(n_confs=10, random_state=42, optimize=True, max_iters=200, missing_value=nan)[source]

Bases: BaseDescriptorTransformer

3-D shape descriptors from an ETKDGv3-embedded, MMFF94-optimized conformer.

Each molecule is protonated and embedded with RDKit’s ETKDGv3 distance geometry algorithm (n_confs trial conformers, seeded via random_state for reproducibility). Every embedded conformer is then geometry-optimized with the MMFF94 force field and the lowest-energy one is kept; the ten shape descriptors of rdkit.Chem.Descriptors3D (principal-moments-of-inertia ratios NPR1/NPR2, asphericity, eccentricity, radius of gyration, spherocity index, …) are then computed on that single best conformer.

Parameters:
  • n_confs (int) – Number of trial conformers generated per molecule; the lowest-MMFF94-energy one (after optimization) is kept.

  • random_state (int) – Seed for the ETKDGv3 embedding (randomSeed), for deterministic, reproducible output.

  • optimize (bool) – Run an MMFF94 geometry minimization on every embedded conformer before ranking by energy. Skipping it (False) is faster but yields noisier, un-relaxed geometries.

  • max_iters (int) – Maximum MMFF94 minimization iterations per conformer.

  • missing_value (float) – Value substituted when embedding fails entirely (e.g. molecules RDKit cannot parametrize, or with fewer than 2 atoms) or a descriptor raises.

Notes

Distance-geometry embedding is inherently stochastic; determinism here comes entirely from fixing randomSeed in AllChem.ETKDGv3(), which is RDKit’s documented approach to reproducible conformer generation.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.descriptors import Descriptors3D
>>> d3d = Descriptors3D(n_confs=2, random_state=0)
>>> X = d3d.fit_transform([Chem.MolFromSmiles("CCO")])
>>> X.shape
(1, 10)

References

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.ConstitutionalDescriptors(missing_value=nan)[source]

Bases: BaseDescriptorTransformer

Constitutional descriptors: simple atom/bond/ring counts.

Constitutional descriptors are the simplest, 0-dimensional family in the Todeschini & Consonni taxonomy: they depend only on molecular composition and connectivity (how many of each atom/bond/ring type), not on any graph-theoretic weighting or 3-D geometry. They are cheap, always defined, and form the backbone of most QSAR descriptor sets.

Parameters:

missing_value (float) – Value substituted when a descriptor raises or returns a non-finite value for a given molecule.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.descriptors import ConstitutionalDescriptors
>>> cd = ConstitutionalDescriptors()
>>> X = cd.fit_transform([Chem.MolFromSmiles("c1ccccc1")])
>>> X.shape[1] == len(cd.get_feature_names_out())
True

References

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.PhysicochemicalDescriptors(missing_value=nan)[source]

Bases: BaseDescriptorTransformer

Core medicinal-chemistry physicochemical property block.

Bundles the handful of whole-molecule properties most commonly used to reason about drug-likeness and ADMET behaviour: molecular weight, octanol-water partition coefficient (Wildman-Crippen MolLogP), topological polar surface area, hydrogen-bond donor/acceptor counts, rotatable-bond count, the fraction of sp3-hybridized carbons, molar refractivity, and the QED drug-likeness score.

Parameters:

missing_value (float) – Value substituted when a descriptor raises or returns a non-finite value for a given molecule.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.descriptors import PhysicochemicalDescriptors
>>> pc = PhysicochemicalDescriptors()
>>> X = pc.fit_transform([Chem.MolFromSmiles("CC(=O)Oc1ccccc1C(=O)O")])
>>> X.shape
(1, 9)

References

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.LipinskiDescriptors(missing_value=nan)[source]

Bases: BaseDescriptorTransformer

Lipinski Rule-of-Five and Veber oral-bioavailability descriptors.

Computes the four Rule-of-Five properties (molecular weight, LogP, hydrogen-bond donor/acceptor counts), the count of Ro5 violations, a PassesLipinski flag (violations <= 1, the conventional tolerance), and Veber’s two additional oral-bioavailability criteria (rotatable bonds <= 10 and TPSA <= 140 A^2) as a PassesVeber flag.

Parameters:

missing_value (float) – Value substituted when a descriptor raises or returns a non-finite value for a given molecule.

Notes

Boolean outcomes are encoded as 1.0/0.0 rather than bool so the block stays a uniform float64 matrix, consistent with every other transformer in qsarkit.representation.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.descriptors import LipinskiDescriptors
>>> ld = LipinskiDescriptors()
>>> X = ld.fit_transform([Chem.MolFromSmiles("CCO")])
>>> bool(X[0, list(ld.get_feature_names_out()).index("PassesLipinski")])
True

References

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.FragmentDescriptors(fragment_names=None, missing_value=nan)[source]

Bases: BaseDescriptorTransformer

SMARTS-based functional-group fragment counts.

rdkit.Chem.Fragments defines roughly 85 hand-curated SMARTS substructure counters (fr_Al_COOH aliphatic carboxylic acid, fr_halogen, fr_benzene, fr_epoxide, …), each counting how many times a specific functional group occurs in the molecule. They are the interpretable, medicinal-chemistry counterpart to a hashed fingerprint and are frequently used as toxicophore/reactivity alerts or as an interpretable QSAR feature block.

Parameters:
  • fragment_names (Optional[Sequence[str]]) – Names of the fr_* functions to compute (must exist on rdkit.Chem.Fragments). None (default) computes every fr_* function RDKit registers, in alphabetical order.

  • missing_value (float) – Value substituted when a fragment counter raises for a given molecule.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.descriptors import FragmentDescriptors
>>> fd = FragmentDescriptors(fragment_names=["fr_benzene", "fr_halogen"])
>>> fd.fit_transform([Chem.MolFromSmiles("c1ccccc1Cl")]).tolist()
[[1.0, 1.0]]

References

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.DescriptorCalculator(blocks=('physicochemical', 'lipinski', 'constitutional', 'fragments'), extra_transformers=None)[source]

Bases: MoleculeTransformer

Facade combining several named descriptor blocks into one design matrix.

QSAR feature engineering rarely uses a single descriptor family in isolation; this transformer selects and concatenates several of the named blocks in qsarkit.representation.descriptors (and, optionally, arbitrary user-supplied MoleculeTransformer instances) behind a single fit/transform call, mirroring qsarkit.representation.fingerprints.FingerprintCombiner for descriptor blocks.

Parameters:
  • blocks (Sequence[str]) – Names of built-in blocks to include, in order. Valid names are "constitutional", "physicochemical", "lipinski", "fragments", "rdkit_all" and "3d".

  • extra_transformers (Optional[Sequence[Tuple[str, MoleculeTransformer]]]) – Additional named transformers appended after the built-in blocks (e.g. a fingerprint, or a custom descriptor transformer). Each must implement fit/transform over Iterable[Mol] and get_feature_names_out().

Variables:

n_features_out (int) – Total width of the concatenated output, set after fit.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.descriptors import DescriptorCalculator
>>> calc = DescriptorCalculator(blocks=["physicochemical", "lipinski"])
>>> X = calc.fit_transform([Chem.MolFromSmiles("CCO")])
>>> X.shape[1] == len(calc.get_feature_names_out())
True

References

fit(mols, y=None)[source]

Fit every member block on the same molecules.

Parameters:
Returns:

self.

Return type:

DescriptorCalculator

get_feature_names_out(input_features=None)[source]

Return prefixed feature names from every member block.

Parameters:

input_features (Optional[Sequence[str]]) – Ignored; present for scikit-learn API compatibility.

Returns:

Array of str names, formatted "<block_name>__<feature>".

Return type:

ndarray[tuple[Any, ...], dtype[object_]]

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

class qsarkit.representation.Mol2VecTransformer(radius=1, vector_size=100, window=10, min_count=3, epochs=10, sg=1, agg='sum', unseen_token='UNK', seed=42, workers=1)[source]

Bases: FittableMoleculeTransformer

Mol2vec: unsupervised molecular embeddings from Morgan-identifier sentences.

Mol2vec treats a molecule as a “sentence” of circular substructure identifiers (Morgan/ECFP-style environments around each atom, one “word” per (atom, radius) pair) and trains a Word2Vec skip-gram model over a corpus of such sentences, exactly as in NLP. A trained model therefore embeds a substructure into a dense vector such that chemically related substructures (e.g. two different aromatic-ring contexts) end up nearby; a whole molecule’s embedding is the (optionally weighted) sum or mean of its substructures’ vectors.

Parameters:
  • radius (int) – Maximum Morgan radius used when building sentences; identifiers for every radius in 0, ..., radius are included per atom.

  • vector_size (int) – Dimensionality of the learned substructure/molecule embeddings.

  • window (int) – Word2Vec context window (in tokens of the sentence).

  • min_count (int) – Minimum corpus frequency for a substructure identifier to get its own vector; rarer identifiers are collapsed into unseen_token (see _insert_unseen_token()) before training, when unseen_token is not None.

  • epochs (int) – Number of Word2Vec training epochs.

  • sg (int) – Word2Vec training algorithm: 1 = skip-gram (the algorithm used in the original paper), 0 = CBOW.

  • agg (str) – How per-substructure vectors are combined into the molecule embedding. The original paper sums them ("sum", the “MOL2VEC” method); "mean" gives a length-normalized alternative.

  • unseen_token (Optional[str]) – Placeholder substituted for identifiers below min_count during training, and used at inference time for any identifier absent from the trained vocabulary. None disables this: substructures not in the vocabulary simply do not contribute to the embedding.

  • seed (int) – Word2Vec training seed, for reproducibility (combined with workers=1 to make training deterministic, since gensim’s multi-threaded training is only reproducible single-threaded).

  • workers (int) – Number of Word2Vec worker threads. Kept at 1 by default because gensim’s Word2Vec training is only bit-for-bit reproducible with a single worker.

Variables:

is_fitted (bool) – Whether fit() (or from_pretrained()) has been called.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.mol2vec import Mol2VecTransformer
>>> mols = [Chem.MolFromSmiles(s) for s in ["CCO", "CCN", "c1ccccc1", "CC(=O)O"]]
>>> m2v = Mol2VecTransformer(vector_size=8, min_count=1, epochs=5)
>>> X = m2v.fit_transform(mols)
>>> X.shape
(4, 8)

References

fit(mols, y=None)[source]

Train the Word2Vec model on the Morgan-identifier sentences of mols.

Parameters:
  • mols (Iterable[Any]) – Training molecules. None entries are ignored.

  • y (Optional[Iterable[Any]]) – Present for scikit-learn API compatibility; Mol2vec training is unsupervised.

Returns:

self.

Return type:

Mol2VecTransformer

Raises:

ValueError – If agg is not "sum"/"mean", or no non-None molecule is supplied.

get_feature_names_out(input_features=None)[source]

Return vector_size embedding-dimension names.

Parameters:

input_features (Optional[Sequence[str]]) – Ignored; present for scikit-learn API compatibility.

Returns:

Array of str names "mol2vec_0", "mol2vec_1", …

Return type:

ndarray[tuple[Any, ...], dtype[object_]]

save(path)[source]

Persist the trained Word2Vec model to disk.

Parameters:

path (str) – Destination path, forwarded to gensim.models.Word2Vec.save.

Return type:

None

classmethod from_pretrained(path, **kwargs)[source]

Load a previously trained (or third-party) Word2Vec checkpoint.

Parameters:
  • path (str) – Path to a Word2Vec model saved via gensim.models.Word2Vec.save (e.g. the public Mol2vec checkpoint distributed by the paper’s authors, model_300dim.pkl: https://github.com/samoturk/mol2vec/tree/master/examples/models).

  • **kwargs (Any) – Extra constructor arguments (e.g. radius, agg) forwarded to Mol2VecTransformer.__init__; use these to match the hyperparameters the checkpoint was trained with.

Returns:

A fitted transformer wrapping the loaded model.

Return type:

Mol2VecTransformer

References

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

qsarkit.representation.mol_to_sentence(mol, radius)[source]

Convert a molecule into its Mol2vec “sentence” of Morgan identifiers.

Reproduces mol2alt_sentence from the reference Mol2vec implementation: a Morgan fingerprint is computed with bit-info tracking (mapping every circular-substructure identifier to the atoms/radii it was generated from); the identifiers are then read back out ordered by atom index and, within an atom, by increasing radius from 0 to radius. The resulting list of identifiers is the “sentence” fed to Word2Vec, with each distinct circular substructure playing the role of a word and each molecule the role of a sentence.

Parameters:
  • mol (Mol) – Molecule to decompose.

  • radius (int) – Maximum Morgan radius; identifiers for every radius in 0, ..., radius are included.

Returns:

The molecule’s sentence, one token per (atom, radius) substructure.

Return type:

List[str]

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation import mol_to_sentence
>>> sentence = mol_to_sentence(Chem.MolFromSmiles("CCO"), radius=1)
>>> len(sentence)
6
>>> all(token.isdigit() or token.lstrip("-").isdigit() for token in sentence)
True

The “sentence” is the Morgan identifier of every atom at every radius up to radius, ordered so that an atom’s identifiers are adjacent – which is what lets a word2vec model learn substructure context. Three atoms at two radii gives six tokens.

References

class qsarkit.representation.ChemBERTaTransformer(model_name='seyonec/ChemBERTa-zinc-base-v1', pooling='mean', max_length=128, batch_size=32, device=None)[source]

Bases: _BaseHFEncoderTransformer

ChemBERTa molecular embeddings from a pretrained SMILES RoBERTa model.

ChemBERTa is a RoBERTa-architecture masked-language model pretrained on millions of SMILES strings from PubChem/ZINC, following the BERT pretrain-then-finetune recipe applied to chemistry. This transformer loads a pretrained checkpoint (by default seyonec/ChemBERTa-zinc-base-v1 from the Hugging Face Hub), encodes each molecule’s canonical SMILES, and pools the final hidden states into a fixed-width embedding usable directly as a QSAR feature matrix.

Parameters:
  • model_name (str) – Hugging Face Hub identifier or local path of a ChemBERTa-family checkpoint. Requires network access on first use (or a local Hugging Face cache / offline path) to download model weights.

  • pooling (str) – Token-pooling strategy; see _BaseHFEncoderTransformer.

  • max_length (int) – Maximum SMILES token length; longer SMILES are truncated.

  • batch_size (int) – Number of molecules encoded per forward pass.

  • device (Optional[str]) – Torch device. None (default) uses CUDA when available, else CPU.

Notes

Loading requires the nlp extra (pip install qsarkit-learn[nlp], which installs torch and transformers) and, for the default checkpoint, either network access to the Hugging Face Hub or a previously populated local HF cache / offline model_name path. No fine-tuning is performed here: embeddings come directly from the pretrained encoder (feature extraction / “frozen ChemBERTa” mode), the setting under which the original paper reports its representation benchmarks.

Examples

>>> from rdkit import Chem
>>> from qsarkit.representation.embeddings import ChemBERTaTransformer
>>> cb = ChemBERTaTransformer()
>>> cb.fit([])
>>> cb.transform([Chem.MolFromSmiles("CCO")]).shape
(1, 768)

References

  • Chithrananda, S., Grand, G. & Ramsundar, B. (2020). “ChemBERTa: Large-Scale Self-Supervised Pretraining for Molecular Property Prediction.” arXiv:2010.09885. https://arxiv.org/abs/2010.09885

  • Liu, Y. et al. (2019). “RoBERTa: A Robustly Optimized BERT Pretraining Approach.” arXiv:1907.11692. https://arxiv.org/abs/1907.11692

  • Pretrained checkpoint: https://huggingface.co/seyonec/ChemBERTa-zinc-base-v1

  • Hugging Face transformers documentation: https://huggingface.co/docs/transformers

set_fit_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_transform_request(*, mols='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

mols (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for mols parameter in transform.

Returns:

self – The updated object.

Return type:

object

References

  • Rogers, D. & Hahn, M. (2010). “Extended-Connectivity Fingerprints.” J. Chem. Inf. Model., 50(5), 742-754. doi:10.1021/ci100050t

  • Durant, J. L. et al. (2002). “Reoptimization of MDL Keys for Use in Drug Discovery.” J. Chem. Inf. Comput. Sci., 42(6), 1273-1280. doi:10.1021/ci010132r

  • Todeschini, R. & Consonni, V. (2009). “Molecular Descriptors for Chemoinformatics.” Wiley. doi:10.1002/9783527628766

  • Jaeger, S., Fulle, S. & Turk, S. (2018). “Mol2vec.” J. Chem. Inf. Model., 58(1), 27-35. doi:10.1021/acs.jcim.7b00616

  • Chithrananda, S., Grand, G. & Ramsundar, B. (2020). “ChemBERTa.” arXiv:2010.09885