### Example CSD.ini Configuration Source: https://downloads.ccdc.cam.ac.uk/documentation/API/installation_notes An example of the CSD.ini configuration file content, used to specify the CSD data location. The 'root' value should be the directory containing the 'csd' data directory. ```ini [General] root=/home/user/CCDC/ccdc-data/ ``` -------------------------------- ### Setup Screener Settings Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/virtual_screening_examples Configures the settings for the CCDC ligand screener, including the output directory. It takes an output directory path as input and returns a Screener.Settings object with the specified directory set. ```python import os from ccdc.screening import Screener def setup_screener(output_dir): """Return the settings object for the ligand screener. :param output_dir: Directory for screener output files :return: Screener settings """ settings = Screener.Settings() settings.output_directory = os.path.join(os.getcwd(), output_dir) return settings ``` -------------------------------- ### Install Optional Third-party Python Packages Source: https://downloads.ccdc.cam.ac.uk/documentation/API/installation_notes Installs essential third-party Python packages required by some example scripts and software distributed with the CSD Python API. Uses pip for installation. ```bash pip install matplotlib jinja2 numpy biopython ``` -------------------------------- ### CSD Python API - Quick Primer Source: https://downloads.ccdc.cam.ac.uk/documentation/API/descriptive_doc_index This section provides a quick primer on using the CSD Python API, covering essential topics to get started. ```APIDOC ## CSD Python API - Quick Primer ### Description This section offers a quick primer to using the CSD Python API, covering the introduction, starting a Python interactive shell, accessing database entries, crystals, and molecules, reading and writing molecules, searching the CSD, conformational geometry analysis, and interaction preference analysis. ### Method N/A (Documentation Overview) ### Endpoint N/A (Documentation Overview) ### Parameters N/A (Documentation Overview) ### Request Example N/A (Documentation Overview) ### Response N/A (Documentation Overview) ``` -------------------------------- ### Build and Install Python from Source on Linux Source: https://downloads.ccdc.cam.ac.uk/documentation/API/installation_notes Compiles and installs Python 3 from source code to a user-defined directory. This process involves configuring build options, making the binaries, and installing them locally. ```bash $ tar zxvf Python-3.11.*.tgz $ cd Python-3.11.* $ ./configure --prefix=$HOME/python3.11 --enable-optimizations --enable-shared $ make $ make install ``` -------------------------------- ### Python Screener Setup and Molecule Screening Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/virtual_screening_examples This Python code demonstrates setting up a 'Screener' object for virtual screening. It reads a query molecule or overlay, generates interaction fields, and then screens a specified set of molecules. The process involves configuring the screener with the output directory, number of threads, and number of conformers. Finally, it writes the screened molecules to a mol2 file and their scores to a CSV file. ```python from ccdc.io import MoleculeReader from ccdc.screening import Screener import os def main(args): mols_to_screen = args.screen_set nt = args.threads nc = args.nconfs output_dir = args.output_directory query = [m for m in MoleculeReader(overlay)] # Read the query mol or overlay of mols settings = setup_screener(output_dir) screener = Screener(query, settings=settings, nthreads=nt) # Generate fields around the input query print('Generated fields for query: %s' % overlay) output_name = os.path.join(settings.output_directory, "screened_molecules.mol2") scores = screen_molecules(screener, mols_to_screen, nc, nt, output_name) # Screen set of molecules output_name_scores = os.path.join(settings.output_directory, "screening_scores.csv") write_scores(scores, output_name_scores) if __name__ == '__main__': main() ``` -------------------------------- ### Start Python Interactive Shell Source: https://downloads.ccdc.cam.ac.uk/documentation/API/descriptive_docs/primer Demonstrates how to start a Python interactive shell, which is used throughout this primer for executing CSD Python API commands. This is a standard Python operation. ```bash bash-3.2$ python Python 2.7.3 (default, Jun 21 2012, 13:00:25) [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ``` -------------------------------- ### Screener Class Initialization and Setup Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/screening Initializes the Screener with overlay molecules and optional settings. It common setup includes handling settings, output directories, and parsing atom types from parameter files. ```python def __init__(self, overlay, settings=None, nthreads=1): '''Initialise the screener. :param overlay: a list of :class:`ccdc.molecule.Molecule` :param settings: a :class:`ccdc.screening.Screener.Settings` instance or ``None``. :param nthreads: int value for the number of threads to use when screening. ''' self._init_common(settings) self._init_from_overlay(overlay,nthreads) def _init_common(self,settings): if settings is None: settings = Screener.Settings() self.settings = settings if self.settings.save_files and os.path.exists(self.settings.output_directory): shutil.rmtree(self.settings.output_directory) self._parse_atom_types() def _init_from_overlay(self,overlay,nthreads): self.overlay = overlay self._screener = LigandScreeningLib.FieldScreeningWorkFlow( [m._molecule for m in self.overlay], self.settings._settings, nthreads ) def _parse_atom_types(self): '''Private: extract atom types from similarity definitions.''' with open(os.path.join(self.settings.parameter_directory, 'similarity_atom_types_new.txt')) as f: self.atom_types = dict( (l.split()[1], True) for l in f if l.startswith('ATOM_TYPE') ).keys() ``` -------------------------------- ### Install Python System-Wide on Linux Source: https://downloads.ccdc.cam.ac.uk/documentation/API/installation_notes Installs Python from source to a system-wide location (e.g., /usr/local) using root privileges. The `altinstall` option is used to avoid overwriting the system's default Python executable. ```bash $ tar zxvf Python-3.11.*.tgz $ cd Python-3.11.* $ ./configure --enable-optimizations --enable-shared $ sudo make altinstall ``` -------------------------------- ### Python Argument Parser Setup for CCDC API Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/crystal_examples Configures an argument parser to accept crystal reference codes or files and an optional output file. It handles the parsing of these arguments and sets up initial attributes for output formatting and file handling. ```python import argparse import os class ReportArgumentParser(argparse.ArgumentParser): def __init__(self): """Set up the argument parser.""" super(self.__class__, self).__init__(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) self.add_argument('refcodes', nargs='+', help='CSD Refcodes or files') self.add_argument('-o', '--output', help='The output file to use. HTML or CSV files can be written.') self.args = self.parse_args() self.output_format = None """:obj:`str` An identifier for the output format to write.""" self.output_file = None """:obj:`str` The full file name of the output file.""" self.output_dir = None """:obj:`str` The directory to hold output files.""" self.diagram_generator = None """:obj:`ccdc.diagram.DiagramGenerator` A diagram generator.""" if not self.args.output: self.output_format = 'stdout' else: if not (self.args.output.endswith('html') or self.args.output.endswith('csv')): raise Exception('Cannot recognise format for output file %s! .html or .csv are valid.' % self.args.output) self.output_file = os.path.abspath(self.args.output) self.output_dir = os.path.dirname(self.output_file) # Make sure the output directory exists if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) if self.output_file: # Assuming DiagramGenerator is available # from ccdc.diagram import DiagramGenerator # self.diagram_generator = DiagramGenerator() # self.diagram_generator.settings.return_type = 'SVG' pass # Placeholder for actual DiagramGenerator instantiation self.output = None if self.args.output.endswith('html'): self.output_format = 'html' elif self.args.output.endswith('csv'): self.output_format = 'csv' ``` -------------------------------- ### Python Argument Parsing Setup Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/cavity_examples Configures command-line arguments for a Python script, including options for output files, exclusion files, and threshold values. It sets default values and specifies data types for each argument. This is typically used at the beginning of a script to handle user inputs. ```python self.add_argument( '-t', '--threshold', help='Threshold below which comparison scores will not be written to the output file', type=float, default=0.0 ) self.add_argument( '-o', '--results_output_file', help='Name of output file for results', default='output.csv' ) self.add_argument( '-x', '--excluded_results_output_file', help='Name of output file for excluded results', default='excluded_output.csv' ) self.args = self.parse_args() self.temp_dir = tempfile.mkdtemp() self.query_sequence_file = 'query.fasta' open(self.query_sequence_file, 'w').close() self.targets_sequence_file = 'targets.fasta' open(self.targets_sequence_file, 'w').close() self.fasta_output_file = 'output.fasta' if not os.path.exists(self.args.database): raise ValueError('The specified database {} does not exist'.format(self.args.database)) ``` -------------------------------- ### Start GOLD Server (Python) Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/docking This private Python method '_start_gold' is intended to initiate the GOLD server process. It checks if the GOLD executable path ('_gold_exe') has been set. If not, it implies that the server cannot be started. This method serves as an entry point for launching the GOLD docking simulation environment. ```python def _start_gold(self, file_name=None, mode='foreground'): '''Private: start the gold server.''' if self._gold_exe is None: ``` -------------------------------- ### Install CSD Python API using Pip (Online) Source: https://downloads.ccdc.cam.ac.uk/documentation/API/installation_notes Installs the CSD Python API from the CCDC pip package repository. This method requires a valid Python environment. ```bash python -m pip install --extra-index-url https://pip.ccdc.cam.ac.uk/ csd-python-api ``` -------------------------------- ### Install CSD Python API using Pip on Windows (Offline) Source: https://downloads.ccdc.cam.ac.uk/documentation/API/installation_notes Installs the CSD Python API from a local .whl file on Windows. May require Visual C++ Redistributable and HTTPS proxy configuration. ```bash pip install csd_python_api-3.5.0-py311-none-win_amd64.whl ``` -------------------------------- ### Install CSD Python API using Conda (Online) Source: https://downloads.ccdc.cam.ac.uk/documentation/API/installation_notes Installs the CSD Python API from the CCDC conda channel. Ensures the conda-forge channel is configured for dependencies. ```bash conda install --channel=https://conda.ccdc.cam.ac.uk csd-python-api ``` ```bash conda config --add channels https://conda.ccdc.cam.ac.uk conda install csd-python-api ``` -------------------------------- ### Example Python Runner Script Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/crystal_examples A basic Python script structure that appears to be the entry point for running a process. It instantiates a 'Runner' class and calls its 'run' method. The script includes a license notice and attribution requirement. ```python #!/usr/bin/env python # # This script can be used for any purpose without limitation subject to the # conditions at https://www.ccdc.cam.ac.uk/Community/Pages/Licences/v2.aspx # # This permission notice and the following statement of attribution must be # included in all copies or substantial portions of this script. if __name__ == '__main__': t = Runner().run() ``` -------------------------------- ### Install Python Build Dependencies on Linux (CentOS) Source: https://downloads.ccdc.cam.ac.uk/documentation/API/installation_notes Installs necessary libraries for compiling Python from source on CentOS 7 and 8 using the yum package manager. These include development tools and libraries for SSL, compression, and database support. ```bash $ sudo yum install -y gcc make openssl-devel bzip2-devel libffi libffi-devel sqlite-devel xz-devel ``` -------------------------------- ### Setup User-Provided Database - Python Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/conformer Sets up a user-defined database by parsing a mogul.path file. It locates the CSD database file, extracts its name, and creates a MogulDataFiles object. Includes error handling for missing database files, logging warnings and disabling ring analysis if necessary. ```python def _setup_database_user(self, mogul_setup, mogul_path): '''Set up a user-provided database :param mogul_setup: A Mogul setup object :param mogul_path: A mogul.path file :return: None ''' mogul_dir = os.path.dirname(mogul_path) mpf = MogulAnalysisLib.MogulPathFile(mogul_path) database = mpf.csd_path() name = mpf.name() if database and os.path.exists(database): db_file = EntryReader(database)._db if not name: name = os.path.splitext(os.path.basename(database))[0] else: db_file = None name = 'No sqlite format database' logger = Logger() logger.warning( f'Unable to locate sqlite database from file: {mogul_path}' ) if self.settings.ring.analyse: logger.warning( 'Turning ring analysis off as no sqlite database found.' ) self.settings.ring.analyse = False df = MogulAnalysisLib.MogulDataFiles(mogul_setup.fragment_types(), mogul_dir, db_file, name) self._database_files.append(df) ``` -------------------------------- ### Get Solubility Data Property in Python with Example Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/entry This Python code retrieves the 'solubility_data' property. It processes experimental solubility measurements, converting them into a list of 'SolubilityMeasurement' objects. The example demonstrates creating an Entry, adding solubility data, and then retrieving it. ```python @property def solubility_data(self): '''Get or set the solubility data, a list of :class:`ccdc.entry.SolubilityMeasurement` >>> from ccdc.entry import Entry, SolubilityMeasurement >>> e=Entry.from_string('CC(C)Cc1ccc(cc1)C(C)C(O)=O') >>> sol = SolubilityMeasurement('21-22', 25, 'mg/L', 'deg.C', 'from PubChem') >>> sol.add_solvent('water', 100) >>> e.solubility_data = [sol] >>> e.solubility_data [SolubilityMeasurement(21 - 22, 25.0, "mg/L", "deg.C", from PubChem)] >>> e.solubility_data[0].solvents (('water', 100.0),) ''' try: experimental_info = self._entry.experimental_info() solubility_info = experimental_info.solubility_info() solubility_measurements = solubility_info.solubility_tests() except AttributeError: solubility_measurements = [] solubility_data = [] for solubility_measurement in solubility_measurements: sol = SolubilityMeasurement( solubility_measurement.solubility(), solubility_measurement.temperature(), solubility_measurement.solubility_units(), solubility_measurement.temperature_units(), solubility_measurement.notes() ) solvent_ratios = solubility_measurement.solvents() for solvent_ratio in solvent_ratios: sol.add_solvent(solvent_ratio[0], solvent_ratio[1]) solubility_data.append(sol) return solubility_data ``` -------------------------------- ### Get Database Files Name Source: https://downloads.ccdc.cam.ac.uk/documentation/API/modules/conformer_api Retrieves the names of the databases, returned as a list of strings. Example: ['CSD', 'Sep25_CIP']. ```python _property _database_files_name Returns: a list of str ``` -------------------------------- ### Setup CSD Databases - Python Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/conformer Initializes CSD databases by reading entry files. It determines database paths, checks for existing data, and creates MogulDataFiles objects. Handles cases where the database file name is a list or a single string, and checks if the data directory exists, potentially creating new entries if not found or if updates are ignored. ```python def _setup_databases_csd(self, mogul_setup, ignore_updates): '''Set up the CSD databases :param mogul_setup: A Mogul setup object :param ignore_updates: Set to True to only set up main CSD database :return: None ''' rdr = EntryReader('csd') if isinstance(rdr.file_name, list): dbs = rdr.file_name else: dbs = [rdr.file_name] for fname in dbs: db = EntryReader(fname) base = os.path.splitext(os.path.basename(fname))[0] possible = os.path.join(mogul_setup.mogul_data(), base) if possible.endswith('_CIP'): possible = possible[:-4] elif possible.endswith('_ASER'): possible = possible[:-5] if os.path.exists(possible): if not ignore_updates: df = MogulAnalysisLib.MogulDataFiles( mogul_setup.fragment_types(), possible, db._db, base ) self._database_files.append(df) else: df = MogulAnalysisLib.MogulDataFiles( mogul_setup.fragment_types(), mogul_setup.mogul_data(), db._db, 'CSD' ) self._database_files.append(df) ``` -------------------------------- ### Accessing CSD Subsets with EntryReader Source: https://downloads.ccdc.cam.ac.uk/documentation/API/modules/io_api Illustrates how to access predefined CSD subsets using the `Subsets` enum with `EntryReader`. This example shows how to get a reader for the MOF subset. ```python mof_reader = EntryReader(subset=Subsets.MOF) ``` -------------------------------- ### Execute Runner Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/cavity_examples This block checks if the script is being run directly and, if so, instantiates the Runner class and calls its run method to start the analysis pipeline. ```python if __name__ == '__main__': Runner().run() ``` -------------------------------- ### Get Molecule Example - Python Source: https://downloads.ccdc.cam.ac.uk/documentation/API/modules/search_api This snippet demonstrates how to retrieve a molecule from the CSD using the EntryReader and then store it for subsequent searches. It requires the 'ccdc.io' module. ```python from ccdc.io import EntryReader csd_reader = EntryReader('CSD') mol = csd_reader.molecule('ACSALA') ``` -------------------------------- ### Setting up Docking Runs with CSD Python API Source: https://downloads.ccdc.cam.ac.uk/documentation/API/descriptive_doc_index Illustrates the process of setting up a molecular docking run using the CSD Python API. This includes preparing the protein and ligand for docking. ```python from ccdc import docking from ccdc.protein import Protein from ccdc.molecule import Molecule # Load protein and ligand protein = Protein.from_file('protein.pdb') ligand = Molecule.from_file('ligand.mol2') # Prepare protein and ligand (example using default preparation) docking_protein = docking.ProteinPreparation().prepare(protein) docking_ligand = docking.LigandPreparation().prepare(ligand) # Set up a docking run (further configuration needed for actual run) docker = docking.Docker() # Example: setting docking parameters (specific parameters depend on the desired run) # docker.parameters.scoring_function = docking.Docker.ScoringFunction.REDUCED_PLComplex print("Docking setup initiated. Further configuration and execution required.") ``` -------------------------------- ### Get Angle Histogram X-Axis Properties - Python Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/interaction Returns the x-axis properties for an angle histogram, specifying the start, stop, and number of bins for plotting purposes. ```python @property def angle_histogram_x_axis_properties(self): '''X-axis properties of angle histogram, :returns: a tuple containing the various x-axis properties needed to plot an angle histogram :rtype::tuple: - (start, stop, number of bins) ''' return self._stats.angle_histogram_x_axis_properties() ``` -------------------------------- ### Setting up a Docking Run Source: https://downloads.ccdc.cam.ac.uk/documentation/API/descriptive_docs/docking Demonstrates the essential steps to set up and execute a protein-ligand docking run using the `ccdc.docking` module, including defining proteins, ligands, and binding sites. ```APIDOC ## Setting up a Docking Run ### Description This section outlines the process of configuring and running a molecular docking simulation using the `ccdc.docking` module. It covers importing necessary modules, defining protein and ligand files, specifying the binding site, setting docking parameters, and initiating the docking process. ### Method `ccdc.docking.Docker` ### Steps 1. **Import modules**: `from ccdc.docking import Docker`, `from ccdc.io import MoleculeReader`. 2. **Initialize Docker**: `docker = Docker()`. 3. **Access Settings**: `settings = docker.settings`. 4. **Add Protein**: `settings.add_protein_file(protein_file_path)`. 5. **Define Binding Site**: Use a ligand and protein to define the binding site, e.g., `settings.binding_site = settings.BindingSiteFromLigand(protein, ligand, radius)`. 6. **Configure Settings**: Set parameters like `fitness_function`, `output_directory`, `output_file`, etc. 7. **Add Ligand(s)**: `settings.add_ligand_file(ligand_file_path, num_runs)`. 8. **Perform Docking**: `results = docker.dock()`. 9. **Check Results**: `results.return_code`. ### Request Example (Python) ```python from ccdc.docking import Docker from ccdc.io import MoleculeReader import tempfile docker = Docker() settings = docker.settings # Add protein MLL1_protein_file = '2w5y_protein_prepared.mol2' settings.add_protein_file(MLL1_protein_file) # Define binding site using native ligand MLL1_native_ligand_file = 'SAH_native.mol2' MLL1_native_ligand = MoleculeReader(MLL1_native_ligand_file)[0] MLL1_protein = settings.proteins[0] settings.binding_site = settings.BindingSiteFromLigand(MLL1_protein, MLL1_native_ligand, 8.0) # Set other parameters settings.fitness_function = 'plp' settings.autoscale = 10. settings.early_termination = False batch_tempd = tempfile.mkdtemp() settings.output_directory = batch_tempd settings.output_file = 'docked_ligands.mol2' # Add ligand to dock MLL1_ligand_file = 'SAH.mol2' settings.add_ligand_file(MLL1_ligand_file, 10) # Perform docking results = docker.dock() # Check return code print(results.return_code) ``` ### Response Example (Console Output) ``` 0 ``` ### Parameters - **`ccdc.docking.Docker.Settings.add_protein_file(file_path: str)`** - Adds a protein file to the docking settings. - **`ccdc.docking.Docker.Settings.BindingSiteFromLigand(protein: ccdc.protein.Protein, ligand: ccdc.molecule.Molecule, distance: float)`** - Creates a binding site definition based on a ligand's position within a protein. - **`ccdc.docking.Docker.Settings.add_ligand_file(file_path: str, num_runs: int)`** - Adds a ligand file to be docked, specifying the number of docking runs per ligand. - **`ccdc.docking.Docker.dock() -> ccdc.docking.Docker.Results`** - Executes the docking process based on the configured settings and returns a `Results` object. - **`ccdc.docking.Docker.Results.return_code`** (int) - The return code of the docking process. 0 typically indicates success. ``` -------------------------------- ### Get Distance Histogram X-Axis Properties - Python Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/interaction Retrieves properties for the x-axis of a distance histogram, including start, stop, and number of bins. This is essential for plotting. ```python @property def distance_histogram_x_axis_properties(self): '''X-axis properties of distance histogram, :returns: a tuple containing the various x-axis properties needed to plot a distance histogram :rtype::tuple: - (start, stop, number of bins) ''' return self._stats.distance_histogram_x_axis_properties() ``` -------------------------------- ### LigandOverlay Class Initialization and Methods Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/descriptors Initializes the LigandOverlay class with a project directory. It includes methods to add ligands for overlay and to generate formatted conformer filenames. This class orchestrates the ligand overlay process. ```python class LigandOverlay(object): '''A class for overlaying ligands and generating pharmacophores.''' # ... (LigandOverlaySolution nested class definition) def __init__(self, project_directory: str): '''Initialise a LigandOverlay object. :param project_directory: directory in which to write the output files ''' self._project_directory = project_directory self._ligands = [] def add_ligands(self, ligands: list[Molecule]) -> None: '''Adds ligands to be overlaid. :param ligands: a list of Molecule to be added ''' self._ligands.extend(ligands) def conformer_file_name(self, index: int, file_name: str) -> str: """Generates a formatted filename with an index prefix, the first 8 characters of the ligand identifier and a '.mol2' extension.""" return f"{index+1:02d}_{os.path.splitext(os.path.basename(file_name))[0][:8]}.mol2" ``` -------------------------------- ### Get base name of file Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/powder_pattern_examples Returns the base name (the filename without the directory path) of a given file path. This is a common utility function for file manipulation. ```python return os.path.basename(file_name) ``` -------------------------------- ### ConformerGenerator Initialization and Settings Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/conformer Initializes the ConformerGenerator with optional settings, thread count, and parameter locator. It performs a license check and loads necessary parameter files. Default settings are applied if none are provided, and defaults from the underlying library are used if specific settings are None. ```python class ConformerGenerator(object): '''Generates conformers for a single or a list of molecules. This functionality is available only under licenced conditions. Please contact support@ccdc.cam.ac.uk for details. ''' _telemetry = 0 def __init__(self, settings=None, skip_minimisation=False, nthreads=1, parameter_locator=DefaultConformerParameterFileLocator()): '''Initialise the ConformerGenerator. :param settings: a :class:`ccdc.conformer.ConformerSettings` instance or ``None``. If ``None`` a default settings will be constructed :param skip_minimisation: whether an input molecule be minimised or not :param nthreads: number of threads on which to run the generation ''' ConformerGeneratorLib.licence_check() self.logger = Logger() if settings is None: settings = ConformerSettings() self.settings = settings parameter_files = parameter_locator.locate() if parameter_files is None: raise RuntimeError("Conformer parameter files not found") self._conformer_generator = ConformerGeneratorLib.GenerateConformersWorkFlow( parameter_files, skip_minimisation, nthreads ) if self.settings.max_conformers is None: self.settings.max_conformers = self._conformer_generator.maximum_number_of_clustered_conformers() if self.settings.max_unusual_torsions is None: self.settings.max_unusual_torsions = self._conformer_generator.max_unusual_torsions() if self.settings.superimpose_conformers_onto_reference is None: self.settings.superimpose_conformers_onto_reference = self._conformer_generator.superimpose_conformers_onto_reference() if self.settings._use_input_torsion_distributions is None: self.settings._use_input_torsion_distributions = self._conformer_generator.use_input_torsion_distribution() if self.settings.max_clash_start_value is None: self.settings.max_clash_start_value = self._conformer_generator.maximum_clash_start_value() if type(self)._telemetry == 0: UtilitiesLib.ccdc_conformer_generation_telemetry() type(self)._telemetry = 1 ``` -------------------------------- ### Get Melting Point of a CCDC Entry Source: https://downloads.ccdc.cam.ac.uk/documentation/API/modules/entry_api This example retrieves the melting point of a crystal structure from a CCDC entry. It uses `EntryReader` to access the entry and then reads the `melting_point` property. ```python from ccdc.io import EntryReader csd_reader = EntryReader('CSD') acsala13 = csd_reader.entry('ACSALA13') print(acsala13.melting_point) ``` -------------------------------- ### Set and Get Notes for Heat Capacity Source: https://downloads.ccdc.cam.ac.uk/documentation/API/modules/entry_api This example shows how to add or retrieve textual notes associated with the heat capacity of a CCDC entry. The `heat_capacity_notes` property is used for this purpose. ```python from ccdc.entry import Entry e=Entry.from_string("OCO") print(e.heat_capacity_notes) e.heat_capacity_notes='from Wikipedia, at 189.78K' print(e.heat_capacity_notes) ``` -------------------------------- ### VisualHabit Class and Settings Source: https://downloads.ccdc.cam.ac.uk/documentation/API/descriptive_docs/visualhabit Demonstrates how to instantiate the VisualHabit class and configure its settings, including specifying a forcefield. ```APIDOC ## VisualHabit Class and Settings ### Description This section covers the instantiation of the `VisualHabit` class and its associated `Settings` class. It details how to configure parameters like the forcefield for calculating intermolecular interactions. ### Method Instantiation and Attribute Assignment ### Endpoint N/A (Object-oriented API) ### Parameters #### Request Body (for Settings) - **potential** (string) - Optional - Specifies the forcefield to be used. Accepts unambiguous prefixes of available forcefield names. ### Request Example ```python from ccdc.morphology import VisualHabit visualhabit_settings = VisualHabit.Settings() visualhabit_settings.potential = 'dreidingII' # Example: Setting the forcefield to Dreiding II ``` ### Response #### Success Response (200) - **VisualHabit.Settings object**: An instance of the settings class, configured with the specified parameters. #### Response Example ```json { "settings_configured": true, "potential": "dreidingII" } ``` ### Available Potentials - **dreidingII**: S.L. Mayo, B.D. Olafson and W.A. Goddard III, J. Phys. Chem. 1990 (94) 8897 - **gavezzotti**: G. Filippini and A. Gavezzotti, Acta Cryst. B49 (1993) 868-880 - **momany**: F.A. Momany, L.M. Carruthers, R.F. McGuire and H.A. Scheraga, J. Phys. Chem. 78 (1974) 1595 - **CLP**: Gavezzotti, A. (2011). New J. Chem. 35, 1360-1368 ``` -------------------------------- ### Docking API - Introduction Source: https://downloads.ccdc.cam.ac.uk/documentation/API/modules/docking_api Introduction to the Docking API and its capabilities. ```APIDOC ## Docking API ### Introduction This API provides functionality related to docking simulations. It includes options to configure output files and manage docking jobs. ``` -------------------------------- ### Get Chemical Name as HTML - Python Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/entry Retrieves the chemical name of the entry formatted as HTML. This property is intended for displaying chemical names in a web context. The example shows how to retrieve it using EntryReader. ```python @property def chemical_name_as_html(self): u'''The chemical name of the entry formatted as HTML. >>> from ccdc.io import EntryReader >>> csd_reader = EntryReader('CSD') >>> e = csd_reader.entry('AACRHA') >>> print(e.chemical_name_as_html) ``` -------------------------------- ### Get Heat of Fusion (Python) Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/entry Retrieves the heat of fusion values and units. It returns a tuple containing the lower bound, optional upper bound, and units. Handles potential AttributeErrors. Requires ccdc.entry.Entry for examples. ```Python try: hf_values = self._experimental_info().solubility_info().heat_of_fusion() hf_unit = self._experimental_info().solubility_info().heat_of_fusion_units() ``` -------------------------------- ### Get Heat Capacity (Python) Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/entry Retrieves the heat capacity value and its units as a tuple. It handles potential AttributeErrors, returning None if the information is not available. This method is part of the solubility information. Requires ccdc.entry.Entry for examples. ```Python try: cp = self._experimental_info().solubility_info().heat_capacity() cp_unit = self._entry.experimental_info().solubility_info().heat_capacity_units() return cp, cp_unit except AttributeError: pass ``` -------------------------------- ### Ligand Preparation Initialization and Rule Loading Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/docking Initializes the LigandPreparation class, either with default settings or custom ones. It loads protonation rules from a specified file or a default location within the CSD database if no file is provided. It checks for the existence of the rules file to determine if rules can be applied. ```python def __init__(self, settings=None): if settings is None: self.settings = Docker.LigandPreparation.Settings() else: self.settings = settings if self.settings.protonation_rules_file is None: rules_dir = io._CSDDatabaseLocator.get_optimisation_parameter_file_location() rules_file = os.path.join(rules_dir, 'protonation_rules.txt') else: rules_file = self.settings.protonation_rules_file if os.path.exists(rules_file): self._protonation_rules = ChemicalAnalysisLib.ProtonationRules(rules_file) else: self._protonation_rules = None ``` -------------------------------- ### Get Heat Capacity Notes (Python) Source: https://downloads.ccdc.cam.ac.uk/documentation/API/_modules/ccdc/entry Retrieves the notes associated with the heat capacity. It handles cases where the notes might not be present, returning an empty string or None depending on the underlying implementation. Requires ccdc.entry.Entry for examples. ```Python try: return self._experimental_info().solubility_info().heat_capacity_notes() except AttributeError: pass ``` -------------------------------- ### Python Script for Protein Docking and Rescoring using CCDC Docker Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/docking_examples This Python script, `docking_and_rescoring.py`, utilizes the CCDC library to perform molecular docking and rescoring. It parses command-line arguments to configure the docking process, including input files, speed, output settings, and fitness functions. The script prepares the protein by cleaning it and then uses a reference ligand to define the binding site for docking. It outputs the results to a specified directory or a temporary one. ```python import argparse import tempfile import os from ccdc.io import EntryWriter, MoleculeReader from ccdc.protein import Protein from ccdc.docking import Docker class Runner(argparse.ArgumentParser): '''Parses arguments, runs the docking.''' def __init__(self): '''Defines the arguments.''' super(self.__class__, self).__init__(description=__doc__) self.add_argument( 'protein_file_name', help='The protein file name' ) self.add_argument( '-l', '--ligand-file-name', help='Ligand file. If not supplied the substrate ligand will be docked. If rescoring only, this file should contain the docked ligands.' ) self.add_argument( '-rl', '--reference-ligand-file-name', help='Reference ligand file.', required=True ) self.add_argument( '-s', '--speed', default='very fast', choices=('very fast', 'fast', 'medium', 'slow', 'very slow'), help='How thorough the docking attempts should be. The values correspond to 10%%, 25%%, 50%%, 75%% and 100%% autoscaling of docking parameters.' ) self.add_argument( '-n', '--ndocks', default=10, type=int, help='Number of docking attempts to run.' ) self.add_argument( '-d', '--directory', help='Output directory for the docking. Default is a temporary directory.' ) self.add_argument( '-f', '--fitness-function', choices=('plp', 'asp', 'chemscore', 'goldscore'), help='Fitness function to use (default None).' ) self.add_argument( '-r', '--rescore-function', choices=('plp', 'asp', 'chemscore', 'goldscore'), help='Rescore function to use (default None)' ) self.args = self.parse_args() self.docker = None self.settings = None self.ref_ligand = None self.protein = None def run(self): '''Run the docking.''' self.create_docker() protein_ligands = self.prepare_protein() self.prepare_ligands(protein_ligands) self.prepare_binding_site() self.dock() def is_rescore(self): return self.args.rescore_function and not self.args.fitness_function def create_docker(self): '''Create a docker.''' self.docker = Docker() self.settings = self.docker.settings if self.args.directory: if not os.path.isdir(self.args.directory): os.makedirs(self.args.directory) else: self.args.directory = tempfile.mkdtemp() self.settings.output_directory = self.args.directory if self.is_rescore(): self.settings.output_file = 'rescored_ligands.mol2' else: self.settings.output_file = 'docked_ligands.mol2' self.settings.output_format = 'mol2' self.settings.autoscale = { 'very fast': 10, 'fast': 25, 'medium': 50, 'slow': 75, 'very slow': 100 }[self.args.speed] self.settings.fitness_function = self.args.fitness_function if self.args.rescore_function: self.settings.rescore_function = self.args.rescore_function if self.args.reference_ligand_file_name: self.settings.reference_ligand_file = self.args.reference_ligand_file_name self.ref_ligand = MoleculeReader(self.args.reference_ligand_file_name)[0] self.settings.reference_ligand_file = self.args.reference_ligand_file_name def prepare_binding_site(self): '''Define the binding site from the reference ligand.''' ligand_cog = self.ref_ligand.centre_of_geometry() self.settings.binding_site = self.settings.BindingSiteFromPoint( None, ligand_cog, 12.0 ) def prepare_protein(self): '''Prepare the protein and remove any ligands.''' self.protein = Protein.from_file(self.args.protein_file_name) self.protein.remove_all_waters() self.protein.remove_unknown_atoms() self.protein.add_hydrogens() ligands = self.protein.ligands for l in ligands: self.protein.remove_ligand(l.identifier) protein_file_name = os.path.join( self.settings.output_directory, 'clean_%s.mol2' % self.protein.identifier ) ``` -------------------------------- ### Python Base Class for Molecule Processors Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/molecular_processing_examples Defines a base class 'MolProcessor' for readers, writers, filters, and transformers. It handles initialization, molecule iteration, processing, logging, and statistics reporting. Dependencies include 'sys', 'os', 'glob', 'argparse', 'logging', 'ccdc.io', 'ccdc.molecule', 'ccdc.search', 'ccdc.utilities.Logger', and 'functools.reduce'. ```python import sys import os import glob import argparse import logging import ccdc.io import ccdc.molecule import ccdc.search from ccdc.utilities import Logger from functools import reduce ############################################################################## class MolProcessor(object): """Base class for readers, writers, filters and transformers.""" def __init__(self, source, **kw): """Updates dictionary with keyword arguments.""" self.source = source self.__dict__.update(kw) self.successes = 0 self.failures = 0 self.logger = Logger() self.logger.ignore_line_numbers() self.logger.set_log_level(logging.INFO) def __str__(self): """Defaults to class name.""" return self.__class__.__name__ __repr__ = __str__ def molecules(self): """Generator for molecules. Yields a molecule.""" for m in self.source.molecules(): m = self.process(m) if m: yield m def process(self, m): """Default to do nothing.""" return m def message(self, *args): """Unconditionally print a message.""" self.logger.info(' '.join(map(str, args))) def log(self, *args): """Log a message if verbose.""" if self.verbose: self.logger.info(' '.join(map(str, args))) def succeed(self, *args): """Register a success, and optionally log it.""" self.successes += 1 if self.verbose: self.logger.info( '%s: succeeded %s' % (self, ' '.join(map(str, args))) ) def fail(self, *args): """Register a failure and optionally log it.""" self.failures += 1 if self.verbose: self.logger.info( '%s: failed %s' % (self, ' '.join(map(str, args))) ) def print_stats(self): """Print statistics on success and failure.""" if self.source is not None: self.source.print_stats() self.logger.info('%6d total, %6d successes, %6d failures, %s' % ( self.successes+self.failures, self.successes, self.failures, self )) @classmethod def long_option(klass): """Construct a sensible long option name.""" s = '-' for k in klass.__name__: if k in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': s += '-' + k.lower() else: s += k return s ``` -------------------------------- ### Get Docking Full Path (Python) Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/docking_examples Generates the complete file path for docking results by joining the directory path and the docking file name. This function depends on get_docking_directory and get_docking_file helper functions. ```python def get_path(base_dir, fitness_function, scoring_function, no_run): return os.path.join( get_docking_directory(base_dir, fitness_function, scoring_function, no_run), get_docking_file(fitness_function, scoring_function, no_run)) ``` -------------------------------- ### Get Atom Counts for a Molecule Source: https://downloads.ccdc.cam.ac.uk/documentation/API/cookbook_examples/crystal_examples Retrieves and formats the counts of each atom type within a molecule. It iterates through the atoms, tallies their symbols, sorts them by count in descending order, and returns a list of strings in the format 'AtomSymbol: Count'. ```python def get_atom_counts(molecule): """Return a list of strings of atom counts.""" atom_cts = collections.defaultdict(int) for atom in molecule.atoms: atom_cts[atom.atomic_symbol] += 1 l = sorted([(v, k) for k, v in atom_cts.items()]) l.reverse() return ['%s: %d' % (k, v) for v, k in l] ``` -------------------------------- ### Instantiate ConformerGenerator - Python Source: https://downloads.ccdc.cam.ac.uk/documentation/API/modules/conformer_api Demonstrates how to instantiate the ConformerGenerator class in Python. Users can optionally provide settings, skip minimization, specify the number of threads, and a parameter locator. ```python from ccdc.conformer import ConformerGenerator # Instantiate with default settings conformer_generator = ConformerGenerator() # Instantiate with custom settings settings = ConformerGenerator.ConformerSettings() settings.max_conformers = 10 conformer_generator = ConformerGenerator(settings=settings, nthreads=4) ``` -------------------------------- ### Generate conformers using CCDC ConformerGenerator Source: https://downloads.ccdc.cam.ac.uk/documentation/API/descriptive_docs/conformer Generates a set of molecular conformers for a given molecule using the configured `ConformerGenerator`. The `generate()` method returns a list of conformers, and the example shows how to get the count of generated conformers. ```python conformers = conformer_generator.generate(mol) len(conformers) ```