### Install Mordred Community Source: https://context7.com/jacksonburns/mordred-community/llms.txt Install the library using pip or conda. The [full] option includes pandas and progress bar support. ```bash pip install mordredcommunity ``` ```bash pip install mordredcommunity[full] ``` ```bash conda install -c conda-forge mordredcommunity ``` -------------------------------- ### Command-Line SASA Calculation Source: https://context7.com/jacksonburns/mordred-community/llms.txt Example of how to calculate Solvent-Accessible Surface Area (SASA) using the mordred command-line interface. ```bash python -m mordred.surface_area molecule.sdf --solvent-radius 1.4 --mesh-level 5 ``` -------------------------------- ### CSV Output Format Example Source: https://context7.com/jacksonburns/mordred-community/llms.txt Illustrates the expected CSV output format for descriptor values, including molecule names and descriptor names as headers. ```text name,ECIndex,WPath,WPol,Zagreb1,... benzene,36,27,3,24.0,... chlorobenzene,45,42,5,30.0,... ``` -------------------------------- ### Initialize and Use Calculator Source: https://context7.com/jacksonburns/mordred-community/llms.txt Initialize the Calculator with descriptor modules. Call the calculator with an RDKit Mol object to get a Result object. Access descriptor values by index or name, and check for missing values. ```python from rdkit import Chem from mordred import Calculator, descriptors, is_missing # All 1826 descriptors (2D + 3D) calc_all = Calculator(descriptors, ignore_3D=False) # Only 2D descriptors (1613) calc_2d = Calculator(descriptors, ignore_3D=True) mol = Chem.MolFromSmiles("c1ccccc1") # benzene result = calc_2d(mol) print(len(calc_2d)) # 1613 print(result[:3]) # first three descriptor values print(result["ABC"]) # access by descriptor name # Check for missing values missing = [v for v in result if is_missing(v)] print(f"Missing descriptors: {len(missing)}") ``` -------------------------------- ### Calculate Descriptors and Return as Pandas DataFrame Source: https://context7.com/jacksonburns/mordred-community/llms.txt Use `Calculator.pandas` for a convenient wrapper that returns results as a pandas DataFrame. Requires pandas installation. `freeze_support()` is needed on Windows. ```python from multiprocessing import freeze_support from rdkit import Chem from mordred import Calculator, descriptors if __name__ == "__main__": freeze_support() mols = [ Chem.MolFromSmiles("c1ccccc1"), Chem.MolFromSmiles("c1ccccc1Cl"), Chem.MolFromSmiles("c1ccccc1C"), ] calc = Calculator(descriptors, ignore_3D=True) df = calc.pandas(mols, quiet=True) print(df.shape) # (3, 1613) print(df["SLogP"]) # 0 1.6880 # 1 2.3400 # 2 2.2480 # Name: SLogP, dtype: float64 # Replace missing values with NaN for numeric operations df_clean = df.fill_missing() print(df_clean.describe()) ``` -------------------------------- ### Calculator.pandas Source: https://context7.com/jacksonburns/mordred-community/llms.txt Convenience wrapper around `map()` that returns results as a `pandas.DataFrame` with descriptor names as column headers. Requires `pandas` to be installed. ```APIDOC ## `Calculator.pandas(mols, nproc=None, nmols=None, quiet=False, ipynb=False, id=-1)` Convenience wrapper around `map()` that returns results as a `pandas.DataFrame` with descriptor names as column headers. Requires `pandas` to be installed (`pip install mordredcommunity[full]`). ```python from multiprocessing import freeze_support from rdkit import Chem from mordred import Calculator, descriptors if __name__ == "__main__": freeze_support() mols = [ Chem.MolFromSmiles("c1ccccc1"), Chem.MolFromSmiles("c1ccccc1Cl"), Chem.MolFromSmiles("c1ccccc1C"), ] calc = Calculator(descriptors, ignore_3D=True) df = calc.pandas(mols, quiet=True) print(df.shape) # (3, 1613) print(df["SLogP"]) # 0 1.6880 # 1 2.3400 # 2 2.2480 # Name: SLogP, dtype: float64 # Replace missing values with NaN for numeric operations df_clean = df.fill_missing() print(df_clean.describe()) ``` ``` -------------------------------- ### Calculate Atomic Surface Area Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.surface_area.md Get the solvent accessible surface area for a specific atom by its index. ```python atomic_sa = sa.atomic_sa(i=0) ``` -------------------------------- ### Initialize Calculator with All Descriptors Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.descriptors.md Initialize a Calculator instance with all available descriptors loaded from the descriptors module. ```python >>> calc = Calculator(descriptors) # all descriptors ``` -------------------------------- ### Calculator Initialization and Usage Source: https://context7.com/jacksonburns/mordred-community/llms.txt Demonstrates how to initialize the Calculator class with different descriptor sets (all, 2D only) and how to use it to compute descriptors for a single molecule. It also shows how to access results and check for missing values. ```APIDOC ## Calculator(descs=None, version=None, ignore_3D=False, config=None) ### Description The main entry point for computing descriptors. Accepts descriptor instances, classes, modules, or iterables at construction time. Calling the calculator with an RDKit `Mol` returns a `Result` object. ### Parameters * **descs** (iterable, optional) - Descriptors to include. Defaults to all descriptors. * **version** (str, optional) - Restricts descriptors to a specific mordred version. * **ignore_3D** (bool, optional) - If True, only 2D descriptors are computed. Defaults to False. * **config** (object, optional) - Configuration object for the calculator. ### Request Example ```python from rdkit import Chem from mordred import Calculator, descriptors, is_missing # All 1826 descriptors (2D + 3D) calc_all = Calculator(descriptors, ignore_3D=False) # Only 2D descriptors (1613) calc_2d = Calculator(descriptors, ignore_3D=True) mol = Chem.MolFromSmiles("c1ccccc1") # benzene result = calc_2d(mol) print(len(calc_2d)) # 1613 print(result[:3]) # first three descriptor values print(result["ABC"]) # access by descriptor name # Check for missing values missing = [v for v in result if is_missing(v)] print(f"Missing descriptors: {len(missing)}") ``` ### Response #### Success Response - **Result object**: Contains computed descriptor values, supporting dictionary conversion, missing-value handling, and pandas DataFrame export. ``` -------------------------------- ### Initialize SurfaceArea from Atomic Data Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.surface_area.md Instantiate the SurfaceArea class by providing atomic radii (plus solvent radius) and atomic coordinates. The mesh level can also be specified. ```python from mordred.surface_area import SurfaceArea import numpy as np radiuses = np.random.rand(10) xyzs = np.random.rand(10, 3) sa = SurfaceArea(radiuses, xyzs, level=4) ``` -------------------------------- ### Get Descriptors in Module Source: https://context7.com/jacksonburns/mordred-community/llms.txt Utility function to yield all concrete Descriptor subclasses found in a given module or package. Used internally by Calculator.register(). ```python from mordred import get_descriptors_in_module from mordred import ABCIndex, Chi, descriptors as desc_pkg # Inspect a single descriptor module abc_descs = list(get_descriptors_in_module(ABCIndex)) print([str(d) for d in abc_descs]) # Inspect Chi module chi_descs = list(get_descriptors_in_module(Chi)) print(len(chi_descs)) # Inspect entire descriptors package (all 50 modules) all_descs = list(get_descriptors_in_module(desc_pkg)) print(len(all_descs)) # Disable recursive submodule search top_only = list(get_descriptors_in_module(desc_pkg, submodule=False)) print(len(top_only)) ``` -------------------------------- ### Get Number of Descriptors Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Retrieves the number of descriptors configured in the Calculator object. This can be used to check the count of 2D or 3D descriptors based on initialization. ```python >>> len(calc.descriptors) 1613 ``` -------------------------------- ### Create SurfaceArea from PDB File Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.surface_area.md Initialize a SurfaceArea object by parsing a PDB file. You can set the solvent radius and mesh level. ```python from mordred.surface_area import SurfaceArea sa_from_pdb = SurfaceArea.from_pdb('input.pdb', solvent_radius=1.4, level=3) ``` -------------------------------- ### Command-line Interface for Surface Area Calculation Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.surface_area.md Use this command to calculate surface area from the command line. Specify the input SDF/MOL file and optionally adjust solvent radius and mesh level. ```console python -m mordred.surface_area -h ``` -------------------------------- ### Load and Use Calculator from JSON Source: https://context7.com/jacksonburns/mordred-community/llms.txt Demonstrates how to load a Calculator object from a JSON payload and use it to compute descriptors for a molecule. ```python from mordred import Calculator from mordkit import Frame # Load calculator from JSON calc2 = Calculator.from_json(payload) assert calc2.to_json() == payload result = calc2(mol) print(result.asdict()) ``` -------------------------------- ### Display Mordred Command-Line Help Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Shows the help message for the mordred command-line interface, detailing available arguments and options for calculating descriptors. ```bash $ python -m mordred --help ``` -------------------------------- ### Command-line Interface Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.surface_area.md The mordred.surface_area module can be used as a command-line tool to calculate surface area from SDF or MOL files. ```APIDOC ## Command-line Usage ```console $ python -m mordred.surface_area [-h] [-s R] [-l L] FILE positional arguments: FILE input sdf/mol file optional arguments: -h, --help show this help message and exit -s R, --solvent-radius R solvent radius (default: 1.4) -l L, --mesh-level L mesh level (default: 5) ``` ``` -------------------------------- ### Initialize Descriptor Calculator Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Initializes a Calculator object from the mordred library, optionally specifying descriptors and whether to ignore 3D descriptors. Requires RDKit for molecule handling. ```python >>> from rdkit import Chem >>> from mordred import Calculator, descriptors # create descriptor calculator with all descriptors >>> calc = Calculator(descriptors, ignore_3D=True) ``` -------------------------------- ### Calculate Descriptors from Multiple Input Files Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Calculates specified descriptors for molecules from multiple SMILES input files. The results are combined into a single output. ```bash $ python -m mordred example.smi example2.smi -d ABCIndex ``` -------------------------------- ### Calculate All Descriptors from SMILES File Source: https://context7.com/jacksonburns/mordred-community/llms.txt Calculate all descriptors for all molecules in a SMILES file using the mordred command-line interface. ```bash python -m mordred molecules.smi ``` -------------------------------- ### Calculate Solvent-Accessible Surface Area (SASA) Source: https://context7.com/jacksonburns/mordred-community/llms.txt The SurfaceArea subpackage provides a standalone solvent-accessible surface area (SASA) calculator for 3D molecules or PDB files. ```python from rdkit import Chem from rdkit.Chem import AllChem from mordred.surface_area import SurfaceArea # Build a 3D conformer for aspirin mol = Chem.MolFromSmiles("CC(=O)Oc1ccccc1C(=O)O") mol = Chem.AddHs(mol) AllChem.EmbedMolecule(mol, AllChem.ETKDG()) AllChem.MMFFOptimizeMolecule(mol) # Compute SASA (solvent radius 1.4 Å, mesh level 4) sa = SurfaceArea.from_mol(mol, solvent_radius=1.4, level=4) # Total surface area total = sum(sa.surface_area()) print(f"Total SASA: {total:.2f} Ų") # Per-atom surface area for i, area in enumerate(sa.surface_area()): if area > 0: print(f" atom {i}: {area:.2f} Ų") ``` -------------------------------- ### Calculator.register Method Source: https://context7.com/jacksonburns/mordred-community/llms.txt Explains how to incrementally add descriptors to an existing Calculator instance using the `register` method. It supports various input types like descriptor instances, classes, modules, and iterables. ```APIDOC ## Calculator.register(desc, version=None, ignore_3D=False) ### Description Incrementally adds descriptors to an existing calculator. Accepts descriptor instances, classes (using their `preset()` method), entire modules, or any iterable of the above. The optional `version` parameter restricts registration to descriptors that existed in that version of mordred. ### Parameters * **desc** (Descriptor, class, module, or iterable) - The descriptor(s) to register. * **version** (str, optional) - Restricts registration to descriptors from a specific mordred version. * **ignore_3D** (bool, optional) - If True, only 2D descriptors are registered. Defaults to False. ### Request Example ```python from rdkit import Chem from mordred import Calculator, is_missing from mordred import Chi, ABCIndex, RingCount calc = Calculator() # Register a specific parameterised descriptor instance calc.register(Chi.Chi(type="path_cluster", order=4)) # Register all preset instances from a descriptor class calc.register(RingCount.RingCount) # Register all descriptors from a module calc.register(ABCIndex) # Reproduce the 1.0.0 descriptor set for reproducibility from mordred import descriptors calc_v1 = Calculator(descriptors, version="1.0.0", ignore_3D=True) print(len(calc_v1)) # 1612 mol = Chem.MolFromSmiles("c1ccccc1Cl") # chlorobenzene result = calc(mol) print(list(result)) ``` ### Response This method modifies the `Calculator` instance in place and does not return a value. ``` -------------------------------- ### Calculator.from_json / Calculator.to_json Source: https://context7.com/jacksonburns/mordred-community/llms.txt Descriptors and calculators are fully serializable to/from JSON, enabling reproducible pipelines and persistent configurations. ```APIDOC ## `Calculator.from_json(obj)` / `Calculator.to_json()` / `Descriptor.to_json()` / `Descriptor.from_json(obj)` Descriptors and calculators are fully serializable to/from JSON, enabling reproducible pipelines and persistent configurations. ```python import json from rdkit import Chem from mordred import Calculator from mordred import ABCIndex, Chi, RingCount mol = Chem.MolFromSmiles("c1ccccc1") calc = Calculator([ ABCIndex.ABCIndex(), Chi.Chi(type="path", order=2), RingCount.RingCount(order=6, is_aromatic=True), ]) # Serialize payload = calc.to_json() print(json.dumps(payload, indent=2)) # [ # {"name": "ABCIndex"}, ``` -------------------------------- ### Calculate Descriptors for Multiple Molecules Source: https://context7.com/jacksonburns/mordred-community/llms.txt Instantiate a Calculator with specific descriptors and then iterate through a dictionary of molecules, calling the calculator on each to obtain their descriptor results as dictionaries. ```python from rdkit import Chem from mordred import Calculator from mordred import ABCIndex, Chi calc = Calculator([ ABCIndex.ABCIndex(), Chi.Chi(type="path", order=2), Chi.Chi(type="path", order=3), ]) molecules = { "benzene": Chem.MolFromSmiles("c1ccccc1"), "chlorobenzene": Chem.MolFromSmiles("c1ccccc1Cl"), "toluene": Chem.MolFromSmiles("c1ccccc1C"), } for name, mol in molecules.items(): result = calc(mol) print(f"{name}: {result.asdict()}") # benzene: {'ABC': 4.242..., 'X2p': 3.808..., 'X3p': 2.723...} # chlorobenzene: {'ABC': 5.059..., 'X2p': 4.404..., 'X3p': 3.173...} # toluene: {'ABC': 5.217..., 'X2p': 4.346..., 'X3p': 3.096...} ``` -------------------------------- ### 3D Descriptors from SDF with Parallel Processing Source: https://context7.com/jacksonburns/mordred-community/llms.txt Calculate 3D descriptors from an SDF file using multiple processes for faster computation. ```bash python -m mordred molecules.sdf -3 -p 4 -o descriptors_3d.csv ``` -------------------------------- ### Calculate Descriptors Serially and in Parallel Source: https://context7.com/jacksonburns/mordred-community/llms.txt Use `Calculator.map` to compute descriptors for multiple molecules. Set `nproc=1` for serial execution or omit for parallel processing. `freeze_support()` is required on Windows. ```python from multiprocessing import freeze_support from rdkit import Chem from mordred import Calculator, descriptors if __name__ == "__main__": freeze_support() # required on Windows smiles_list = [ "c1ccccc1", # benzene "c1ccccc1Cl", # chlorobenzene "c1ccccc1C", # toluene "CC(=O)Oc1ccccc1C(=O)O", # aspirin ] mols = [Chem.MolFromSmiles(s) for s in smiles_list] calc = Calculator(descriptors, ignore_3D=True) # Serial execution for result in calc.map(mols, nproc=1, quiet=True): print(result["SLogP"]) # 1.688 # 2.340 # 2.248 # 1.192 # Parallel execution (uses all CPU cores by default) results = list(calc.map(mols, quiet=True)) print(f"Computed {len(results)} result sets, each with {len(results[0])} descriptors") ``` -------------------------------- ### Create SurfaceArea from RDKit Mol Object Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.surface_area.md Construct a SurfaceArea object directly from an RDKit molecule. Specify the conformer ID, solvent radius, and mesh level. ```python from mordred.surface_area import SurfaceArea from rdkit import Chem mol = Chem.MolFromSmiles('CCO') sa_from_mol = SurfaceArea.from_mol(mol, conformer=-1, solvent_radius=1.4, level=4) ``` -------------------------------- ### Import and Inspect Descriptors Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.descriptors.md Import the Calculator and descriptors modules. Inspect the name of a specific descriptor module (ABCIndex) and the total number of available descriptor modules. ```python >>> from mordred import Calculator, descriptors >>> descriptors.ABCIndex.__name__ # ABCIndex module 'mordred.ABCIndex' >>> len(descriptors.all) # all descriptor modules 50 ``` -------------------------------- ### Serializing and Deserializing Calculators and Descriptors Source: https://context7.com/jacksonburns/mordred-community/llms.txt Calculators and descriptors can be fully serialized to and from JSON, facilitating reproducible pipelines and persistent configurations. ```python import json from rdkit import Chem from mordred import Calculator from mordred import ABCIndex, Chi, RingCount mol = Chem.MolFromSmiles("c1ccccc1") calc = Calculator([ ABCIndex.ABCIndex(), Chi.Chi(type="path", order=2), RingCount.RingCount(order=6, is_aromatic=True), ]) # Serialize payload = calc.to_json() print(json.dumps(payload, indent=2)) # [ # {"name": "ABCIndex"}, ``` -------------------------------- ### Process Multiple Input Files Source: https://context7.com/jacksonburns/mordred-community/llms.txt Combine descriptor calculations from multiple input files into a single output CSV, with options for selective descriptor computation. ```bash python -m mordred dataset1.smi dataset2.smi -d ABCIndex -o combined.csv ``` -------------------------------- ### Save Descriptor Results to CSV with Progress Bar Source: https://context7.com/jacksonburns/mordred-community/llms.txt Calculate descriptors and save the results to a CSV file, displaying a progress bar during the process. ```bash python -m mordred molecules.smi -o descriptors.csv ``` -------------------------------- ### Register Descriptors Incrementally Source: https://context7.com/jacksonburns/mordred-community/llms.txt Use the `register` method to add descriptors to an existing Calculator instance. This allows for flexible configuration by adding specific instances, classes, or entire modules. ```python from rdkit import Chem from mordred import Calculator, is_missing from mordred import Chi, ABCIndex, RingCount calc = Calculator() # Register a specific parameterised descriptor instance calc.register(Chi.Chi(type="path_cluster", order=4)) # Register all preset instances from a descriptor class calc.register(RingCount.RingCount) # Register all descriptors from a module calc.register(ABCIndex) # Reproduce the 1.0.0 descriptor set for reproducibility from mordred import descriptors calc_v1 = Calculator(descriptors, version="1.0.0", ignore_3D=True) print(len(calc_v1)) # 1612 mol = Chem.MolFromSmiles("c1ccccc1Cl") # chlorobenzene result = calc(mol) print(list(result)) ``` -------------------------------- ### Calculator Class Methods Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/index.md Methods for managing and using the Calculator for descriptor computations. ```APIDOC ## Calculator Class ### Description Manages the calculation of molecular descriptors. ### Methods #### `from_json(json_data)` Creates a Calculator instance from JSON data. #### `register_json(json_data)` Registers descriptors from JSON data. #### `to_json()` Serializes the Calculator configuration to JSON. #### `config()` Returns the current configuration of the Calculator. #### `descriptors()` Returns a list of registered descriptors. #### `register(descriptor)` Registers a new descriptor with the Calculator. #### `echo(mol)` Calculates and returns descriptors for a molecule. #### `map(mols)` Calculates descriptors for a list of molecules. #### `pandas(mols)` Calculates descriptors for a list of molecules and returns a pandas DataFrame. ``` -------------------------------- ### SurfaceArea Class Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.surface_area.md The SurfaceArea class calculates the solvent accessible surface area for a given molecule. It can be initialized with atomic radii, positions, and a mesh level, or constructed from RDKit Mol objects or PDB files. ```APIDOC ## class mordred.surface_area.SurfaceArea(radiuses, xyzs, level=4) Bases: `object` calculate solvent accessible surface area. * **Parameters:** * **radiuses** (*np.ndarray* *(**dtype=float* *,* *shape=* *(**N* *,* *)* *)*) – atomic radius + solvent radius vector * **xyzs** (*np.ndarray* *(**dtype=float* *,* *shape=* *(**N* *,* *3* *)* *)*) – atomic position matrix * **level** (*int*) – mesh level. subdivide icosahedron n-1 times. $$ N_{ m points} = 5 \times 4^{level} - 8 $$ ### atomic_sa(i) Calculate atomic surface area. * **Parameters:** **i** (*int*) – atom index * **Return type:** float ### surface_area() Calculate all atomic surface area. * **Return type:** [float] ### *classmethod* from_mol(mol, conformer=-1, solvent_radius=1.4, level=4) Construct SurfaceArea from rdkit Mol type. * **Parameters:** * **mol** (*rdkit.Chem.Mol*) – input molecule * **conformer** (*int*) – conformer id * **solvent_radius** (*float*) – solvent radius * **level** (*int*) – mesh level * **Return type:** [SurfaceArea](#mordred.surface_area.SurfaceArea) ### *classmethod* from_pdb(pdb, solvent_radius=1.4, level=3) ``` -------------------------------- ### Calculate Number of Descriptors Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Calculates and prints the total number of 2D and 3D descriptors available in the Calculator. Requires importing Calculator and descriptors from the mordred library. ```python >>> from mordred import Calculator, descriptors >>> n_all = len(Calculator(descriptors, ignore_3D=False).descriptors) >>> n_2D = len(Calculator(descriptors, ignore_3D=True).descriptors) >>> print("2D: {:5} 3D: {:5} ------------ total: {:5}".format(n_2D, n_all - n_2D, n_all)) ``` -------------------------------- ### pandas(mols, nproc=None, nmols=None, quiet=False, ipynb=False, id=-1) Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/mordred.md Calculates descriptors for a given iterable of molecules and returns them as a pandas DataFrame. ```APIDOC ## pandas ### Description Calculate descriptors over mols. ### Parameters * **mols** (*Iterable* *[**rdkit.Mol* *]*) – moleculars * **nproc** (*int*) – number of process to use. default: multiprocessing.cpu_count() * **nmols** (*int*) – number of all mols to use in progress-bar. default: mols._\_len_()_ * **quiet** (*bool*) – don’t show progress bar. default: False * **ipynb** (*bool*) – use ipython notebook progress bar. default: False * **id** (*int*) – conformer id to use. default: -1. ### Returns pandas.DataFrame ``` -------------------------------- ### Calculate Multiple Specific Descriptors Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Calculates multiple specified descriptors (e.g., ABCIndex and AcidBase) for molecules in a SMILES file. Multiple -d flags can be used. ```bash $ python -m mordred example.smi -d ABCIndex -d AcidBase ``` -------------------------------- ### Calculate All Descriptors from SMILES Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Calculates all available molecular descriptors for molecules listed in an input SMILES file and outputs the results to stdout. The output includes a header row with descriptor names. ```bash $ python -m mordred example.smi ``` -------------------------------- ### Descriptor Class Methods Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/index.md Methods for interacting with Descriptor objects, including calculation, serialization, and parameter management. ```APIDOC ## Descriptor Class ### Description Represents a molecular descriptor. ### Methods #### `preset(preset_name)` Loads a descriptor preset. #### `parameters()` Returns the parameters of the descriptor. #### `to_json()` Serializes the descriptor to JSON. #### `calculate(mol)` Calculates the descriptor for a given molecule. #### `dependencies()` Returns the dependencies of the descriptor. #### `fail(exception)` Sets the descriptor to a failed state with an exception. #### `rethrow_zerodiv()` Rethrows ZeroDivisionError if it occurred during calculation. #### `rethrow_na()` Rethrows NA error if it occurred during calculation. #### `from_json(json_data)` Deserializes a descriptor from JSON data. ### Attributes #### `mol` The molecule associated with the descriptor. #### `coord` The coordinate information for the descriptor. #### `as_argument` Represents the descriptor as an argument. ``` -------------------------------- ### Matrix Aggregating Methods Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/index.md Various methods for aggregating descriptor values in a matrix format. ```APIDOC ## Matrix Aggregating Methods ### Description These methods are used for aggregating descriptor values, often in the context of matrix operations. ### Methods - **SpAbs** - **SpMax** - **SpDiam** - **SpAD** - **SpMAD** - **LogEE** - **SM1** - **VE1** - **VE2** - **VE3** - **VR1** - **VR2** - **VR3** ### Usage These methods are typically applied to collections of descriptor results to produce aggregated values. ``` -------------------------------- ### get_descriptors_in_module(mdl, submodule=True) Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/mordred.md Retrieves all descriptors available within a specified module, with an option to search recursively into submodules. ```APIDOC ## get_descriptors_in_module ### Description Get descriptors in module. ### Parameters * **mdl** (*module*) – module to search * **submodule** (*bool*) – search recursively ### Returns Iterator[Descriptor] ``` -------------------------------- ### MultipleFragments Exception Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.error.md Raised when multiple fragments are detected on a require_connected Descriptor. ```APIDOC ## exception mordred.error.MultipleFragments Bases: [`MordredException`](#mordred.error.MordredException) multiple fragments detected on require_connected Descriptor. ``` -------------------------------- ### Calculate Total Surface Area Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.surface_area.md Compute the total solvent accessible surface area for all atoms in the molecule. ```python total_sa = sa.surface_area() ``` -------------------------------- ### map(mols, nproc=None, nmols=None, quiet=False, ipynb=False, id=-1) Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/mordred.md Calculates descriptors for a given iterable of molecules. Supports parallel processing and progress bar customization. ```APIDOC ## map ### Description Calculate descriptors over mols. ### Parameters * **mols** (*Iterable* *[**rdkit.Mol* *]*) – moleculars * **nproc** (*int*) – number of process to use. default: multiprocessing.cpu_count() * **nmols** (*int*) – number of all mols to use in progress-bar. default: mols._\_len_()_ * **quiet** (*bool*) – don’t show progress bar. default: False * **ipynb** (*bool*) – use ipython notebook progress bar. default: False * **id** (*int*) – conformer id to use. default: -1. ### Returns Iterator[Result[scalar]] ``` -------------------------------- ### Calculate Specific Descriptors (ABCIndex) Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Calculates only the ABCIndex descriptor for molecules in a SMILES file and outputs the results. Use the -d flag followed by the descriptor name. ```bash $ python -m mordred example.smi -d ABCIndex ``` -------------------------------- ### Utility Function Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/index.md Function to retrieve descriptors available within a specific module. ```APIDOC ## `get_descriptors_in_module(module)` ### Description Retrieves a list of descriptor names available in the specified module. ### Parameters #### `module` (module) - Required - The module to inspect for descriptors. ``` -------------------------------- ### Descriptor Arithmetic Source: https://context7.com/jacksonburns/mordred-community/llms.txt Descriptor instances support Python arithmetic operators (`+`, `-`, `*`, `/`, `**`, etc.), creating composite descriptors that can be registered into a calculator and serialized to JSON. ```APIDOC ## Descriptor Arithmetic Descriptor instances support Python arithmetic operators (`+`, `-`, `*`, `/`, `**`, etc.), creating composite descriptors that can be registered into a calculator and serialized to JSON. ```python from rdkit import Chem from mordred import ABCIndex, Chi, Calculator benzene = Chem.MolFromSmiles("c1ccccc1") abc = ABCIndex.ABCIndex() chi2 = Chi.Chi(type="path", order=2) # Arithmetic creates a new Descriptor product = abc * chi2 ratio = abc / chi2 shifted = abc + 1.0 calc = Calculator([abc, chi2, product, ratio, shifted]) result = calc(benzene) print(str(product), result[str(product)]) # (ABC*X2p) 16.162... print(str(ratio), result[str(ratio)]) # (ABC/X2p) 1.113... # Serialize and restore the full calculator import json json_data = calc.to_json() calc2 = Calculator.from_json(json_data) result2 = calc2(benzene) assert list(result) == list(result2) ``` ``` -------------------------------- ### Save Descriptors to CSV with Progress Bar Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Calculates molecular descriptors from a SMILES file and saves them to a CSV file. Displays a progress bar during the calculation. ```bash $ python -m mordred example.smi -o example.csv ``` -------------------------------- ### Calculator.__call__ - Single Molecule Calculation Source: https://context7.com/jacksonburns/mordred-community/llms.txt Details the process of calling a `Calculator` instance directly on an RDKit `Mol` object to compute all registered descriptors. It also explains the use of the optional `id` parameter for selecting conformers in 3D calculations. ```APIDOC ## Calculator.__call__(mol, id=-1) ### Description Calling a `Calculator` instance directly on an RDKit `Mol` computes all registered descriptors and returns a `Result`. The optional `id` selects the conformer index for 3D descriptors. ### Parameters * **mol** (rdkit.Chem.rdchem.Mol) - The RDKit molecule object. * **id** (int, optional) - The index of the conformer to use for 3D descriptors. Defaults to -1 (the first conformer). ### Request Example ```python from rdkit import Chem from mordred import Calculator from mordred import ABCIndex, Chi calc = Calculator([ ABCIndex.ABCIndex(), Chi.Chi(type="path", order=2), Chi.Chi(type="path", order=3), ]) molecules = { "benzene": Chem.MolFromSmiles("c1ccccc1"), "chlorobenzene": Chem.MolFromSmiles("c1ccccc1Cl"), "toluene": Chem.MolFromSmiles("c1ccccc1C"), } for name, mol in molecules.items(): result = calc(mol) print(f"{name}: {result.asdict()}") # benzene: {'ABC': 4.242..., 'X2p': 3.808..., 'X3p': 2.723...} # chlorobenzene: {'ABC': 5.059..., 'X2p': 4.404..., 'X3p': 3.173...} # toluene: {'ABC': 5.217..., 'X2p': 4.346..., 'X3p': 3.096...} ``` ### Response #### Success Response - **Result object**: A `Result` object containing the computed descriptor values for the molecule. ``` -------------------------------- ### Performing Arithmetic Operations on Descriptors Source: https://context7.com/jacksonburns/mordred-community/llms.txt Descriptor instances support standard arithmetic operators to create composite descriptors. These can be registered into a calculator and serialized. ```python from rdkit import Chem from mordred import ABCIndex, Chi, Calculator benzene = Chem.MolFromSmiles("c1ccccc1") abc = ABCIndex.ABCIndex() chi2 = Chi.Chi(type="path", order=2) # Arithmetic creates a new Descriptor product = abc * chi2 ratio = abc / chi2 shifted = abc + 1.0 calc = Calculator([abc, chi2, product, ratio, shifted]) result = calc(benzene) print(str(product), result[str(product)]) # (ABC*X2p) 16.162... print(str(ratio), result[str(ratio)]) # (ABC/X2p) 1.113... # Serialize and restore the full calculator import json json_data = calc.to_json() calc2 = Calculator.from_json(json_data) result2 = calc2(benzene) assert list(result) == list(result2) ``` -------------------------------- ### Calculate Descriptors for Multiple Molecules and Convert to Pandas DataFrame Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Calculates molecular descriptors for a list of RDKit Mol objects and returns the results as a pandas DataFrame. This is efficient for analyzing multiple molecules. ```python # calculate multiple molecule >>> mols = [Chem.MolFromSmiles(smi) for smi in ['c1ccccc1Cl', 'c1ccccc1O', 'c1ccccc1N']] # as pandas >>> df = calc.pandas(mols) >>> df['SLogP'] 0 2.3400 1 1.3922 2 1.2688 Name: SLogP, dtype: float64 ``` -------------------------------- ### mordred.Descriptor Class Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/mordred.md The abstract base class for all descriptors in the mordred package. ```APIDOC ## class mordred.Descriptor Abstract base class of descriptors. ### Methods #### *classmethod* preset(version) Generate preset descriptor instances. * **Returns:** preset descriptors * **Return type:** Iterable[[Descriptor](#mordred.Descriptor)] #### *abstractmethod* parameters() **[abstractmethod]** get __init__ arguments of this descriptor instance. this method used in pickling and identifying descriptor instance. * **Returns:** tuple of __init__ arguments * **Return type:** tuple #### to_json() Convert to json serializable dictionary. * **Returns:** dictionary of descriptor * **Return type:** dict #### *abstractmethod* calculate() **[abstractmethod]** calculate descriptor value. * **Returns:** rtype #### dependencies() Descriptor dependencies. * **Returns:** dict[str, Descriptor or None] or None #### fail(exception) Raise known exception and return missing value. * **Raises:** **MissingValueException** – #### rethrow_zerodiv() **[contextmanager]** treat zero div as known exception. #### rethrow_na(exception) **[contextmanager]** treat any exceptions as known exception. #### *classmethod* from_json(obj) Create Descriptor instance from json dict. * **Parameters:** **obj** (*dict*) – descriptor dict * **Returns:** descriptor * **Return type:** [Descriptor](#mordred.Descriptor) ### Properties #### mol target molecule * **Type:** rdkit.Mol #### as_argument Argument representation of descriptor. * **Returns:** any #### mol Get molecule. * **Returns:** rdkit.Mol #### coord Get 3D coordinate. * **Returns:** coordinate matrix * **Return type:** numpy.array[3, N] ``` -------------------------------- ### MordredException Exception Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.error.md Base exception class for mordred-specific errors. ```APIDOC ## exception mordred.error.MordredException Bases: `Exception` ``` -------------------------------- ### Missing Class Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.error.md Represents a known errored value, inheriting from MissingValueBase. ```APIDOC ## class mordred.error.Missing(error, stack) Bases: [`MissingValueBase`](#mordred.error.MissingValueBase) known errored value. #### header *= 'Missing'* ``` -------------------------------- ### Stream Read Descriptors with Progress Bar Hidden Source: https://github.com/jacksonburns/mordred-community/blob/main/README.md Calculates molecular descriptors from a SMILES file using a streaming approach for low memory usage and saves them to a CSV file. The progress bar is hidden. ```bash $ python -m mordred example.smi -s -o example.csv ``` -------------------------------- ### Timeout Exception Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.error.md Raised when a calculation exceeds the allowed time limit. ```APIDOC ## exception mordred.error.Timeout Bases: [`MordredException`](#mordred.error.MordredException) calculation timed out. ``` -------------------------------- ### Calculator.map Source: https://context7.com/jacksonburns/mordred-community/llms.txt Calculates descriptors over an iterable of molecules, optionally in parallel using multiple processes. Returns a generator of Result objects. Set `nproc=1` for single-process execution. ```APIDOC ## `Calculator.map(mols, nproc=None, nmols=None, quiet=False, ipynb=False, id=-1)` Calculates descriptors over an iterable of molecules, optionally in parallel using multiple processes. Returns a generator of `Result` objects. Set `nproc=1` for single-process execution (e.g., in environments where multiprocessing is unsupported). ```python from multiprocessing import freeze_support from rdkit import Chem from mordred import Calculator, descriptors if __name__ == "__main__": freeze_support() # required on Windows smiles_list = [ "c1ccccc1", # benzene "c1ccccc1Cl", # chlorobenzene "c1ccccc1C", # toluene "CC(=O)Oc1ccccc1C(=O)O", # aspirin ] mols = [Chem.MolFromSmiles(s) for s in smiles_list] calc = Calculator(descriptors, ignore_3D=True) # Serial execution for result in calc.map(mols, nproc=1, quiet=True): print(result["SLogP"]) # 1.688 # 2.340 # 2.248 # 1.192 # Parallel execution (uses all CPU cores by default) results = list(calc.map(mols, quiet=True)) print(f"Computed {len(results)} result sets, each with {len(results[0])} descriptors") ``` ``` -------------------------------- ### Selective Descriptor Calculation and Quiet Mode Source: https://context7.com/jacksonburns/mordred-community/llms.txt Calculate only specified descriptors (e.g., ABCIndex and Chi) and suppress the progress bar output. ```bash python -m mordred molecules.smi -d ABCIndex -d Chi -q ``` -------------------------------- ### Result Object Source: https://context7.com/jacksonburns/mordred-community/llms.txt `Result` wraps the output of a single-molecule calculation. It supports index access, name-based access, iteration, missing-value filtering, and dictionary conversion. ```APIDOC ## `Result` — Descriptor Result Object `Result` wraps the output of a single-molecule calculation. It supports index access, name-based access, iteration, missing-value filtering, and dictionary conversion. ```python from rdkit import Chem from mordred import Calculator, descriptors, is_missing calc = Calculator(descriptors, ignore_3D=False) mol = Chem.MolFromSmiles("c1ccccc1") result = calc(mol) # Access by position print(result.ix[0]) # first descriptor value print(result[0]) # same, shorthand # Access by descriptor name print(result.name["C2SP3"]) print(result["SLogP"]) # Iterate over (descriptor, value) pairs for desc, val in result.items(): if not is_missing(val): print(f"{desc}: {val}") break # Remove descriptors that produced missing values (e.g., 3D on 2D mol) valid = result.drop_missing() print(f"Valid: {len(valid)}/{len(result)}") # Replace missing values with NaN instead of removing them filled = result.fill_missing(value=float("nan")) print(len(filled)) # same length as original # Convert to plain dict d = result.asdict() # keys are str descriptor names d_raw = result.asdict(rawkey=True) # keys are Descriptor instances ``` ``` -------------------------------- ### Handle Missing and Error Values Source: https://context7.com/jacksonburns/mordred-community/llms.txt When a descriptor cannot be computed, mordred returns Missing or Error instead of raising. The is_missing() helper detects both. ```python from rdkit import Chem from mordred import Calculator, descriptors, is_missing from mordred.error import Missing, Error, MultipleFragments # 3D descriptors on a 2D-only molecule produce Missing values calc = Calculator(descriptors, ignore_3D=False) mol = Chem.MolFromSmiles("c1ccccc1") # no 3D coordinates result = calc(mol) for desc, val in result.items(): if is_missing(val): if isinstance(val, Missing): print(f"[Known missing] {desc}: {val.error}") elif isinstance(val, Error): print(f"[Unexpected error] {desc}: {val.error}") break # Disconnected molecules trigger MultipleFragments for require_connected descriptors frag_mol = Chem.MolFromSmiles("c1ccccc1.CC") result2 = calc(frag_mol) errors = [(str(d), v) for d, v in result2.items() if is_missing(v)] any_multifrag = any(isinstance(v.error, MultipleFragments) for _, v in errors) print(f"MultipleFragments errors present: {any_multifrag}") ``` -------------------------------- ### DuplicatedDescriptorName Exception Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.error.md Raised when a descriptor has a duplicated string representation. ```APIDOC ## exception mordred.error.DuplicatedDescriptorName(a, b) Bases: [`MordredException`](#mordred.error.MordredException) duplicated string replisantation of descriptor. ``` -------------------------------- ### Error Class Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/subpackages/mordred.error.md Represents an unknown errored value, inheriting from MissingValueBase. ```APIDOC ## class mordred.error.Error(error, stack) Bases: [`MissingValueBase`](#mordred.error.MissingValueBase) unknown errored value. #### header *= 'ERROR'* ``` -------------------------------- ### mordred.Calculator Class Source: https://github.com/jacksonburns/mordred-community/blob/main/docs/mordred.md The Calculator class is used to compute molecular descriptors for given molecules. ```APIDOC ## class mordred.Calculator(descs=None, version=None, ignore_3D=False, config=None) descriptor calculator. * **Parameters:** * **descs** – see Calculator.register() method * **ignore_3D** – see Calculator.register() method ### Methods #### *classmethod* from_json(obj) Create Calculator from json descriptor objects. * **Parameters:** **obj** (*list* *or* *dict*) – descriptors to register * **Returns:** calculator * **Return type:** [Calculator](#mordred.Calculator) #### register_json(obj) Register Descriptors from json descriptor objects. * **Parameters:** **obj** (*list* *or* *dict*) – descriptors to register #### to_json() Convert descriptors to json serializable data. * **Returns:** descriptors * **Return type:** list #### config(**configs) Set global configuration. #### register(desc, version=None, ignore_3D=False) Register descriptors. Descriptor-like: : * Descriptor instance: self * Descriptor class: use Descriptor.preset() method * module: use Descriptor-likes in module * Iterable: use Descriptor-likes in Iterable * **Parameters:** * **desc** (*Descriptor-like*) – descriptors to register * **version** (*str*) – version * **ignore_3D** (*bool*) – ignore 3D descriptors #### echo(s, file=<_io.TextIOWrapper name='' mode='w' encoding='utf-8'>, end='\n') Output message. * **Parameters:** * **s** (*str*) – message to output * **file** (*file-like*) – output to * **end** (*str*) – end mark of message * **Returns:** None ### Properties #### descriptors All descriptors. you can get/set/delete descriptor. * **Returns:** registered descriptors * **Return type:** tuple[[Descriptor](#mordred.Descriptor)] ``` -------------------------------- ### Stream-Read Large Files for Low Memory Usage Source: https://context7.com/jacksonburns/mordred-community/llms.txt Process large molecular files in a streaming mode to minimize memory consumption, suitable for very large datasets. ```bash python -m mordred large_library.smi -s -o output.csv ```