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
Rogers, D. & Hahn, M. (2010). “Extended-Connectivity Fingerprints.” J. Chem. Inf. Model., 50(5), 742-754. https://doi.org/10.1021/ci100050t
RDKit: Open-source cheminformatics. https://www.rdkit.org
- class qsarkit.representation.BaseFingerprintTransformer[source]¶
Bases:
MoleculeTransformerAbstract base for dense, fixed-width molecular fingerprints.
Notes
Noneentries 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 byqsarkit.chemistry.MolecularStandardizer. Output arrays are alwaysfloat64so that fingerprints compose directly with downstream scikit-learn estimators/scalers without an implicit cast; the intermediate RDKit bit/count vectors are generated in their naturaluint8/uint32dtype for efficiency and cast on assignment into the output matrix.References
RDKit documentation, “Fingerprinting and Molecular Similarity”: https://www.rdkit.org/docs/GettingStartedInPython.html#fingerprinting-and-molecular-similarity
scikit-learn transformer API: https://scikit-learn.org/stable/developers/develop.html
- get_feature_names_out(input_features=None)[source]¶
Return
n_features_outbit/count names.- Parameters:
input_features (
Optional[Sequence[str]]) – Ignored; present for scikit-learn API compatibility.- Returns:
Array of
strnames, one per output column.- Return type:
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
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- qsarkit.representation.fold_on_bits(on_bits, n_bits)[source]¶
Fold a sparse list of set bit indices into a dense
n_bitsvector.- Parameters:
- Returns:
float64array of lengthn_bitsholding 0/1 values.- Return type:
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
RDKit documentation, “Fingerprinting and Molecular Similarity”: https://www.rdkit.org/docs/GettingStartedInPython.html#fingerprinting-and-molecular-similarity
- class qsarkit.representation.MorganFingerprint(n_bits=2048, radius=2, use_counts=False, use_features=False, use_chirality=False, use_bond_types=True)[source]¶
Bases:
BaseFingerprintTransformerMorgan (circular) fingerprints, i.e. ECFP and FCFP.
Iteratively hashes the circular atom environment of every atom up to
radiusbonds and folds the resulting identifiers inton_bits. Withuse_features=Falsethe atom invariants are connectivity based (ECFP flavour); withuse_features=Truethey are the Gobbi-style pharmacophoric feature invariants (FCFP flavour). The ECFP diameter naming convention corresponds to2 * radius(radius=2-> ECFP4).- Parameters:
n_bits (
int) – Width of the folded fingerprint.radius (
int) – Maximum circular environment radius, in bonds.use_counts (
bool) – IfTruereturn 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 ton_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
Rogers, D. & Hahn, M. (2010). “Extended-Connectivity Fingerprints.” J. Chem. Inf. Model., 50(5), 742-754. https://doi.org/10.1021/ci100050t
Morgan, H. L. (1965). “The Generation of a Unique Machine Description for Chemical Structures.” J. Chem. Doc., 5(2), 107-113. https://doi.org/10.1021/c160017a018
RDKit
rdFingerprintGeneratordocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.rdFingerprintGenerator.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.FeatureMorganFingerprint(n_bits=2048, radius=2, use_counts=False, use_chirality=False, use_bond_types=True)[source]¶
Bases:
MorganFingerprintFCFP-flavoured Morgan fingerprint (pharmacophoric atom invariants).
Thin convenience subclass of
MorganFingerprintwithuse_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:
References
Rogers, D. & Hahn, M. (2010). “Extended-Connectivity Fingerprints.” J. Chem. Inf. Model., 50(5), 742-754. https://doi.org/10.1021/ci100050t
Gobbi, A. & Poppinger, D. (1998). “Genetic Optimization of Combinatorial Libraries.” Biotechnol. Bioeng., 61(1), 47-54. https://doi.org/10.1002/(SICI)1097-0290(199824)61:1<47::AID-BIT9>3.0.CO;2-Z
RDKit
rdFingerprintGeneratordocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.rdFingerprintGenerator.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- 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:
BaseFingerprintTransformerThe RDKit topological (Daylight-like) path fingerprint.
Enumerates all linear and branched subgraphs of the molecule with a number of bonds between
min_pathandmax_path, hashes each one and setsn_bits_per_hashbits per subgraph in ann_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
RDKit documentation, “RDKit fingerprint”: https://www.rdkit.org/docs/RDKit_Book.html#rdkit-fingerprints
RDKit
rdFingerprintGenerator.GetRDKitFPGeneratordocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.rdFingerprintGenerator.htmlDaylight Theory Manual, “Fingerprints”: https://www.daylight.com/dayhtml/doc/theory/theory.finger.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.PatternFingerprint(n_bits=2048, tautomeric=False)[source]¶
Bases:
BaseFingerprintTransformerRDKit 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)wheneverqueryis a substructure oftarget. 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:
Notes
This fingerprint is binary only: RDKit does not expose a count variant, so no
use_countsparameter is offered.References
RDKit Book, “Pattern fingerprints”: https://www.rdkit.org/docs/RDKit_Book.html#pattern-fingerprints
Landrum, G. RDKit: Open-source cheminformatics. https://www.rdkit.org
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.LayeredFingerprint(n_bits=2048, min_path=1, max_path=7, layer_flags=4294967295, branched_paths=True)[source]¶
Bases:
BaseFingerprintTransformerRDKit layered fingerprint (substructure fingerprint with atom layers).
Like
RDKitFingerprintit hashes subgraphs, but each subgraph is described through several independent “layers” (pure topology, bond order, atom types, ring membership, …), selected bylayer_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
RDKit Book, “Layered fingerprints”: https://www.rdkit.org/docs/RDKit_Book.html#layered-fingerprints
Landrum, G. RDKit: Open-source cheminformatics. https://www.rdkit.org
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.AtomPairFingerprint(n_bits=2048, min_distance=1, max_distance=30, use_counts=True, use_chirality=False)[source]¶
Bases:
BaseFingerprintTransformerCarhart 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 betweenmin_distanceandmax_distance. Atom types encode element, number of heavy-atom neighbours and number of pi electrons. The triplets are hashed inton_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
Carhart, R. E., Smith, D. H. & Venkataraghavan, R. (1985). “Atom Pairs as Molecular Features in Structure-Activity Studies: Definition and Applications.” J. Chem. Inf. Comput. Sci., 25(2), 64-73. https://doi.org/10.1021/ci00046a002
RDKit
rdFingerprintGenerator.GetAtomPairGeneratordocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.rdFingerprintGenerator.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.TopologicalTorsionFingerprint(n_bits=2048, torsion_size=4, use_counts=True, use_chirality=False)[source]¶
Bases:
BaseFingerprintTransformerNilakantan topological-torsion fingerprint.
Enumerates every linear path of
torsion_sizeconsecutively bonded non-hydrogen atoms (four by default, i.e. a torsion) and hashes the ordered tuple of their atom types inton_bits. Torsions complement atom pairs by encoding short-range, shape-relevant connectivity.- Parameters:
References
Nilakantan, R., Bauman, N., Dixon, J. S. & Venkataraghavan, R. (1987). “Topological Torsion: A New Molecular Descriptor for SAR Applications. Comparison with Other Descriptors.” J. Chem. Inf. Comput. Sci., 27(2), 82-85. https://doi.org/10.1021/ci00054a008
RDKit
rdFingerprintGenerator.GetTopologicalTorsionGeneratordocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.rdFingerprintGenerator.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.MACCSKeysFingerprint(drop_unused_bit=False)[source]¶
Bases:
BaseFingerprintTransformer166 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 keyklands at indexk. Set toTrueto 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 non_bits/radius/use_countsparameters 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
Durant, J. L., Leland, B. A., Henry, D. R. & Nourse, J. G. (2002). “Reoptimization of MDL Keys for Use in Drug Discovery.” J. Chem. Inf. Comput. Sci., 42(6), 1273-1280. https://doi.org/10.1021/ci010132r
RDKit
rdkit.Chem.MACCSkeysdocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.MACCSkeys.html
- get_feature_names_out(input_features=None)[source]¶
Return
n_features_outbit/count names.- Parameters:
input_features (
Optional[Sequence[str]]) – Ignored; present for scikit-learn API compatibility.- Returns:
Array of
strnames, one per output column.- Return type:
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
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.AvalonFingerprint(n_bits=512, use_counts=False, is_query=False, bit_flags=15761407)[source]¶
Bases:
BaseFingerprintTransformerAvalon 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’savalonSSSBitssimilarity 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
Gedeck, P., Rohde, B. & Bartels, C. (2006). “QSAR - How Good Is It in Practice? Comparison of Descriptor Sets on an Unbiased Cross Section of Corporate Data Sets.” J. Chem. Inf. Model., 46(5), 1924-1936. https://doi.org/10.1021/ci050413p
RDKit
rdkit.Avalon.pyAvalonToolsdocumentation: https://www.rdkit.org/docs/source/rdkit.Avalon.pyAvalonTools.html
- DEFAULT_BIT_FLAGS¶
RDKit’s default Avalon similarity bit flags (
avalonSimilarityBits).
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.PharmacophoreFingerprint(n_bits=2048)[source]¶
Bases:
BaseFingerprintTransformerGobbi 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 onton_bitscolumns, which keeps the output dense and machine-learning ready. PassNoneto 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. Setn_bits=Noneto 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
Gobbi, A. & Poppinger, D. (1998). “Genetic Optimization of Combinatorial Libraries.” Biotechnol. Bioeng., 61(1), 47-54. https://doi.org/10.1002/(SICI)1097-0290(199824)61:1<47::AID-BIT9>3.0.CO;2-Z
RDKit
rdkit.Chem.Pharm2Ddocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.Pharm2D.htmlRDKit Book, “2D pharmacophore fingerprints”: https://www.rdkit.org/docs/RDKit_Book.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- 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:
BaseFingerprintTransformerMHFP6 - MinHashed fingerprint of circular substructure SMILES.
The molecule is decomposed into the set of canonical SMILES of all circular substructures (“shingles”) up to
radiusbonds; that set is then compressed with MinHash inton_permutations32-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
uint32MinHash vector of lengthn_permutations. This is the representation used for MinHash-LSH nearest-neighbour search.fold=TrueReturn 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 whenfold=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_countsis 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
Probst, D. & Reymond, J.-L. (2018). “A Probabilistic Molecular Fingerprint for Big Data Settings.” J. Cheminform., 10, 66. https://doi.org/10.1186/s13321-018-0321-8
Broder, A. Z. (1997). “On the Resemblance and Containment of Documents.” Proc. Compression and Complexity of Sequences, 21-29. https://doi.org/10.1109/SEQUEN.1997.666900
Reference implementation: https://github.com/reymond-group/mhfp
RDKit
rdkit.Chem.rdMHFPFingerprintdocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.rdMHFPFingerprint.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.MAP4Fingerprint(n_permutations=2048, radius=2, max_distance=None, n_bits=2048, fold=False, isomeric=False, seed=42)[source]¶
Bases:
BaseFingerprintTransformerMAP4 - MinHashed atom-pair fingerprint of radius 2.
MAP4 merges the two ideas behind
AtomPairFingerprintandMHFPFingerprint: for every pair of atoms(i, j)and every radiusr <= radius, the canonical SMILES of the circular substructures aroundiandjare paired with their topological distancedinto 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 whenfold=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 whenfold=True.fold (
bool) – Fold the MinHash vector modulon_bitsinto 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 themhfppackage 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
Capecchi, A., Probst, D. & Reymond, J.-L. (2020). “One Molecular Fingerprint to Rule Them All: Drugs, Biomolecules, and the Metabolome.” J. Cheminform., 12, 43. https://doi.org/10.1186/s13321-020-00445-4
Probst, D. & Reymond, J.-L. (2018). “A Probabilistic Molecular Fingerprint for Big Data Settings.” J. Cheminform., 10, 66. https://doi.org/10.1186/s13321-018-0321-8
Reference implementation: https://github.com/reymond-group/map4
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.FingerprintCombiner(transformers, weights=None)[source]¶
Bases:
MoleculeTransformerHorizontally 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.
FingerprintCombinerfits 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 implementfit/transform(orfit_transform) overIterable[Mol]and return a 2-Dnumpy.ndarraywith a consistent number of rows. Names are used to prefixget_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 afterfit.
Notes
This mirrors the intent of
sklearn.pipeline.FeatureUnionbut is specialized to theIterable[Mol]input contract used throughout qsarkit (FeatureUnionitself works fine with these transformers too; this class exists for a lighter-weight, dependency-free alternative and for symmetry withqsarkit.transform.MoleculeFeatureUnion, which wraps the same pattern for theqsarkit.transformnamespace).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
Pedregosa et al. (2011). “Scikit-learn: Machine Learning in Python.” J. Mach. Learn. Res., 12, 2825-2830. https://jmlr.org/papers/v12/pedregosa11a.html
scikit-learn
FeatureUniondocumentation: https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.htmlNembri, S. et al. (2016). “In Silico Prediction of Cytochrome P450-Drug Interaction: QSARs for CYP3A4 and CYP2C9.” Int. J. Mol. Sci., 17(6), 914. https://doi.org/10.3390/ijms17060914 (example of combined fingerprint + descriptor QSAR feature sets).
- fit(mols, y=None)[source]¶
Fit every member transformer on the same molecules.
- Parameters:
- Returns:
self.
- Return type:
- get_feature_names_out(input_features=None)[source]¶
Return prefixed feature names from every member transformer.
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.BaseDescriptorTransformer[source]¶
Bases:
MoleculeTransformerAbstract 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 aNoneinput molecule – keeping the output positionally aligned with the input, as elsewhere inqsarkit.representation.Catching a bare
Exceptionaround 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.Ipcon 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
RDKit documentation, “List of Available Descriptors”: https://www.rdkit.org/docs/GettingStartedInPython.html#list-of-available-descriptors
- 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
strnames, one per output column.- Return type:
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
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.RDKitDescriptors(descriptor_names=None, missing_value=nan)[source]¶
Bases:
BaseDescriptorTransformerEvery 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 (notablyIpcon large fused-ring systems) can raise or overflow toinf/nanon some molecules; both cases are substituted withmissing_value.- Parameters:
descriptor_names (
Optional[Sequence[str]]) – Names of the descriptors to compute (must be keys ofrdkit.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
Landrum, G. RDKit: Open-source cheminformatics. https://www.rdkit.org
RDKit documentation, “List of Available Descriptors”: https://www.rdkit.org/docs/GettingStartedInPython.html#list-of-available-descriptors
Todeschini, R. & Consonni, V. (2009). “Molecular Descriptors for Chemoinformatics.” Wiley-VCH. https://doi.org/10.1002/9783527628766
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.Descriptors3D(n_confs=10, random_state=42, optimize=True, max_iters=200, missing_value=nan)[source]¶
Bases:
BaseDescriptorTransformer3-D shape descriptors from an ETKDGv3-embedded, MMFF94-optimized conformer.
Each molecule is protonated and embedded with RDKit’s ETKDGv3 distance geometry algorithm (
n_confstrial conformers, seeded viarandom_statefor reproducibility). Every embedded conformer is then geometry-optimized with the MMFF94 force field and the lowest-energy one is kept; the ten shape descriptors ofrdkit.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
randomSeedinAllChem.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
Riniker, S. & Landrum, G. A. (2015). “Better Informed Distance Geometry: Using What We Know To Improve Conformation Generation.” J. Chem. Inf. Model., 55(12), 2562-2574. https://doi.org/10.1021/acs.jcim.5b00654
Halgren, T. A. (1996). “Merck Molecular Force Field. I. Basis, Form, Scope, Parameterization, and Performance of MMFF94.” J. Comput. Chem., 17(5-6), 490-519. https://doi.org/10.1002/(SICI)1096-987X(199604)17:5/6%3C490::AID-JCC1%3E3.0.CO;2-P
RDKit
rdkit.Chem.Descriptors3Ddocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.Descriptors3D.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.ConstitutionalDescriptors(missing_value=nan)[source]¶
Bases:
BaseDescriptorTransformerConstitutional 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
Todeschini, R. & Consonni, V. (2009). “Molecular Descriptors for Chemoinformatics.” Wiley-VCH. https://doi.org/10.1002/9783527628766
RDKit
rdkit.Chem.rdMolDescriptorsdocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.rdMolDescriptors.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.PhysicochemicalDescriptors(missing_value=nan)[source]¶
Bases:
BaseDescriptorTransformerCore 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
Wildman, S. A. & Crippen, G. M. (1999). “Prediction of Physicochemical Parameters by Atomic Contributions.” J. Chem. Inf. Comput. Sci., 39(5), 868-873. https://doi.org/10.1021/ci990307l
Ertl, P., Rohde, B. & Selzer, P. (2000). “Fast Calculation of Molecular Polar Surface Area as a Sum of Fragment-Based Contributions and Its Application to the Prediction of Drug Transport Properties.” J. Med. Chem., 43(20), 3714-3717. https://doi.org/10.1021/jm000942e
Bickerton, G. R. et al. (2012). “Quantifying the Chemical Beauty of Drugs.” Nat. Chem., 4(2), 90-98. https://doi.org/10.1038/nchem.1243
RDKit
rdkit.Chem.QEDdocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.QED.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.LipinskiDescriptors(missing_value=nan)[source]¶
Bases:
BaseDescriptorTransformerLipinski 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
PassesLipinskiflag (violations <= 1, the conventional tolerance), and Veber’s two additional oral-bioavailability criteria (rotatable bonds <= 10 and TPSA <= 140 A^2) as aPassesVeberflag.- 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.0rather thanboolso the block stays a uniformfloat64matrix, consistent with every other transformer inqsarkit.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
Lipinski, C. A., Lombardo, F., Dominy, B. W. & Feeney, P. J. (2001). “Experimental and Computational Approaches to Estimate Solubility and Permeability in Drug Discovery and Development Settings.” Adv. Drug Deliv. Rev., 46(1-3), 3-25. https://doi.org/10.1016/S0169-409X(96)00423-1
Veber, D. F. et al. (2002). “Molecular Properties That Influence the Oral Bioavailability of Drug Candidates.” J. Med. Chem., 45(12), 2615-2623. https://doi.org/10.1021/jm020017n
RDKit
rdkit.Chem.Lipinskidocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.Lipinski.html
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.FragmentDescriptors(fragment_names=None, missing_value=nan)[source]¶
Bases:
BaseDescriptorTransformerSMARTS-based functional-group fragment counts.
rdkit.Chem.Fragmentsdefines roughly 85 hand-curated SMARTS substructure counters (fr_Al_COOHaliphatic 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:
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
Landrum, G. RDKit: Open-source cheminformatics. https://www.rdkit.org
RDKit
rdkit.Chem.Fragmentsdocumentation: https://www.rdkit.org/docs/source/rdkit.Chem.Fragments.htmlErtl, P. (2017). “An Algorithm to Identify Functional Groups in Organic Molecules.” J. Cheminform., 9, 36. https://doi.org/10.1186/s13321-017-0225-z
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- class qsarkit.representation.DescriptorCalculator(blocks=('physicochemical', 'lipinski', 'constitutional', 'fragments'), extra_transformers=None)[source]¶
Bases:
MoleculeTransformerFacade 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-suppliedMoleculeTransformerinstances) behind a singlefit/transformcall, mirroringqsarkit.representation.fingerprints.FingerprintCombinerfor 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 implementfit/transformoverIterable[Mol]andget_feature_names_out().
- Variables:
n_features_out (
int) – Total width of the concatenated output, set afterfit.
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
Todeschini, R. & Consonni, V. (2009). “Molecular Descriptors for Chemoinformatics.” Wiley-VCH. https://doi.org/10.1002/9783527628766
scikit-learn
FeatureUniondocumentation: https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.html
- fit(mols, y=None)[source]¶
Fit every member block on the same molecules.
- Parameters:
- Returns:
self.
- Return type:
- get_feature_names_out(input_features=None)[source]¶
Return prefixed feature names from every member block.
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- 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:
FittableMoleculeTransformerMol2vec: 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 in0, ..., radiusare 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 intounseen_token(see_insert_unseen_token()) before training, whenunseen_tokenis notNone.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 belowmin_countduring training, and used at inference time for any identifier absent from the trained vocabulary.Nonedisables this: substructures not in the vocabulary simply do not contribute to the embedding.seed (
int) – Word2Vec training seed, for reproducibility (combined withworkers=1to 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) – Whetherfit()(orfrom_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
Jaeger, S., Fulle, S. & Turk, S. (2018). “Mol2vec: Unsupervised Machine Learning Approach with Chemical Intuition.” J. Chem. Inf. Model., 58(1), 27-35. https://doi.org/10.1021/acs.jcim.7b00616
Mikolov, T. et al. (2013). “Distributed Representations of Words and Phrases and Their Compositionality.” NeurIPS 2013, 3111-3119. https://papers.nips.cc/paper/5021
Reference implementation: https://github.com/samoturk/mol2vec
gensim
Word2Vecdocumentation: https://radimrehurek.com/gensim/models/word2vec.html
- fit(mols, y=None)[source]¶
Train the Word2Vec model on the Morgan-identifier sentences of
mols.- Parameters:
- Returns:
self.
- Return type:
- Raises:
ValueError – If
aggis not"sum"/"mean", or no non-Nonemolecule is supplied.
- classmethod from_pretrained(path, **kwargs)[source]¶
Load a previously trained (or third-party) Word2Vec checkpoint.
- Parameters:
path (
str) – Path to a Word2Vec model saved viagensim.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 toMol2VecTransformer.__init__; use these to match the hyperparameters the checkpoint was trained with.
- Returns:
A fitted transformer wrapping the loaded model.
- Return type:
References
Jaeger, S., Fulle, S. & Turk, S. (2018). J. Chem. Inf. Model., 58(1), 27-35. https://doi.org/10.1021/acs.jcim.7b00616
Pretrained checkpoints: https://github.com/samoturk/mol2vec
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
- qsarkit.representation.mol_to_sentence(mol, radius)[source]¶
Convert a molecule into its Mol2vec “sentence” of Morgan identifiers.
Reproduces
mol2alt_sentencefrom 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 toradius. 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 in0, ..., radiusare included.
- Returns:
The molecule’s sentence, one token per (atom, radius) substructure.
- Return type:
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
Jaeger, S., Fulle, S. & Turk, S. (2018). “Mol2vec: Unsupervised Machine Learning Approach with Chemical Intuition.” J. Chem. Inf. Model., 58(1), 27-35. https://doi.org/10.1021/acs.jcim.7b00616
Reference implementation: https://github.com/samoturk/mol2vec
- class qsarkit.representation.ChemBERTaTransformer(model_name='seyonec/ChemBERTa-zinc-base-v1', pooling='mean', max_length=128, batch_size=32, device=None)[source]¶
Bases:
_BaseHFEncoderTransformerChemBERTa 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-v1from 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
nlpextra (pip install qsarkit-learn[nlp], which installstorchandtransformers) and, for the default checkpoint, either network access to the Hugging Face Hub or a previously populated local HF cache / offlinemodel_namepath. 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
transformersdocumentation: https://huggingface.co/docs/transformers
- set_fit_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_transform_request(*, mols='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.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(seesklearn.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 totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.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.
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