Lomap Legacy API#
- class lomap.dbmol.DBMolecules(directory: str, parallel: int = 1, verbose: Literal['off', 'info', 'pedantic'] = 'off', time: int = 20, ecrscore: float = 0.0, threed: bool = False, max3d: float = 1000.0, element_change: bool = True, output: bool = False, name: str = 'out', output_no_images: bool = False, output_no_graph: bool = False, display: bool = False, allow_tree: bool = False, max: int = 6, cutoff: float = 0.4, radial: bool = False, hub: str | None = None, fast: bool = False, links_file: str | None = None, known_actives_file: str | None = None, max_dist_from_actives: int = 2, use_common_core: bool = True, shift: bool = True)#
This class is used as a container for all the Molecules
Initialization of the Molecule Database Class.
- Parameters:
directory (str) – Path to the directory containing mol2 and/or sdf input files.
parallel (int, default 1) – Number of processes to use when computing the similarity score matrices.
verbose (str, default 'off') – Logging verbosity; one of
'off','info', or'pedantic'.time (int, default 20) – Maximum time in seconds allowed for each pairwise MCS search.
ecrscore (float, default 0.0) – Electrostatic score override applied when two molecules have different formal charges. A value of 0.0 disables cross-charge comparisons.
threed (bool, default False) – If
True, symmetry-equivalent MCSes are filtered to prefer the one with the best real-space 3D alignment.max3d (float, default 1000.0) – MCS atom pairs further apart than this distance (Angstrom) are removed. The default of 1000.0 is effectively no filter.
element_change (bool, default True) – If
True, allow element changes between mapped atoms.output (bool, default False) – If
True, write output files (graph, images, pickle).name (str, default 'out') – File name prefix used when writing output files.
output_no_images (bool, default False) – If
True, skip generation of 2D image output files.output_no_graph (bool, default False) – If
True, skip generation of the graph.dotfile.display (bool, default False) – If
True, display the generated graph with Matplotlib.allow_tree (bool, default False) – If
True, the final graph does not require a cycle covering and may be a tree.max (int, default 6) – Maximum diameter of the resulting graph.
cutoff (float, default 0.4) – Minimum Similarity Score (MSS) used to build the graph.
radial (bool, default False) – If
True, build a radial graph around the hub compound.hub (str or None, default None) – Name of the molecule to use as the hub in a radial graph.
fast (bool, default False) – If
True, use fast graph building when creating a radial graph. Ifradialis notTrueandhubis not set, this will be ignored.links_file (str or None, default None) – Path to a file listing molecule pairs that should be seeded as links in the graph.
known_actives_file (str or None, default None) – Path to a file listing molecules whose activity is known.
max_dist_from_actives (int, default 2) – Maximum number of graph edges separating any molecule from a known active.
use_common_core (bool, default True) – If
True, search for a common core across all input molecules to seed and speed up pairwise MCS calculations.shift (bool, default True) – If
True, whenthreedis alsoTrue, translate molecules to maximise 3D overlap before evaluating the alignment.
- build_graph() Graph#
Build the perturbation network graph from the computed score matrices.
Optionally writes output files and displays the graph.
- Returns:
The generated perturbation network graph.
- Return type:
nx.Graph
- build_matrices() tuple[SMatrix, SMatrix]#
Compute the pairwise similarity score matrices for all loaded molecules.
Work will be distributed between
self.parallelprocesses.
- compute_mtx(a: int, b: int, strict_mtx: Any, loose_mtx: Any, true_strict_mtx: Any, MCS_map: dict[tuple[int, int], str] | Any) None#
Compute a chunk of the similarity score matrices.
The chunk spans linear indices
atob(inclusive) of the upper-triangle of the symmetric score matrix stored as a flat array.- Parameters:
a (int) – Start index of the chunk to compute.
b (int) – End index (inclusive) of the chunk to compute.
strict_mtx (SMatrix or multiprocessing.Array) – Flat array for strict similarity scores, shared across processes. Can be
multiprocessing.Array.loose_mtx (SMatrix | Any) – Flat array for loose similarity scores, shared across processes. Can be
multiprocessing.Array.true_strict_mtx (SMatrix | Any) – Flat array that stores the strict score before any forced-link override is applied. Can be
multiprocecssing.Array.MCS_map (dict[tuple[int, int], str] | Any) – Mapping from molecule-index pairs to their MCS atom-index map strings, shared across processes. Can be multiprocessing dict.
- next() Molecule#
Return the next molecule in the database sequence.
- Returns:
The next molecule in the database.
- Return type:
- Raises:
StopIteration – When all molecules have been yielded.
- nums() int#
Return the total number of molecules in the database.
- Returns:
Number of molecules currently stored.
- Return type:
- parse_known_actives_file(actives_file: str) None#
Parse a known-actives file and mark the listed molecules as active.
All pairs of known actives are automatically added as prespecified links with a score of 1.0 forced into the graph.
- parse_links_file(links_file: str) None#
Parse a links file and register the specified molecule pairs.
Each line may have the form
mol1 mol2,mol1 mol2 score, ormol1 mol2 score force. Theforcekeyword causes the link to be included in the final graph regardless of its score.
- class lomap.dbmol.SMatrix(shape: tuple[int, ...], dtype: type = <class 'float'>, buffer: ~numpy.ndarray | None = None, offset: int = 0, strides: tuple[int, ...] | None = None, order: ~typing.Literal['K', 'A', 'C', 'F'] | None = None)#
This class implements a “basic” interface for symmetric matrices subclassing ndarray. The class internally stores a bi-dimensional numpy array as a linear array A[k], however the user can still access to the matrix elements by using a two indices notation A[i,j]
- class lomap.dbmol.Molecule(molecule: Mol, mol_id: int, molname: str)#
This Class stores the Rdkit molecule objects, their identification number and the total number of instantiated molecules
- Parameters:
- Raises:
ValueError – If
moleculeis not an RDKit molecule ormolnameis not a string.
- getID() int#
Return the molecule’s integer identifier.
- Returns:
Unique identifier assigned to this molecule.
- Return type:
- getMolecule() Mol#
Return a copy of the underlying RDKit molecule object.
- Returns:
A copy of the stored RDKit molecule.
- Return type:
Chem.Mol
- getName() str#
Return the molecule’s file name.
- Returns:
Basename of the file from which this molecule was loaded.
- Return type:
- class lomap.mcs.MCS(moli: Mol, molj: Mol, time: int = 20, verbose: Literal['debug', 'info', 'warning', 'error', 'critical'] = 'info', max3d: float = 1000.0, threed: bool = False, element_change: bool = True, seed: str | None = None, shift: bool = True)#
This class is used to compute the Maximum Common Subgraph (MCS) between two RDKit molecule objects and to score their similarity by using defined rules.
Initialization function
- Parameters:
moli (Chem.Mol) – The first molecule used to perform the MCS calculation.
molj (Chem.Mol) – The second molecule used to perform the MCS calculation.
time (int, default 20) – Timeout of MCS algorithm in seconds, passed to RDKit.
verbose (Literal["debug", "info", "warning", "error", "critical"], default 'info') – Logging level, defines verbosity of generated logs.
max3d (float, default 1000.0) – The MCS is trimmed to remove atoms which are further apart than this distance (in units of Angstrom). The default, 1000.0, essentially tries not to trim.
threed (bool, default False) – When disambiguating the substructure found back to the original molecules, if
True3D coordinates are used, otherwise the number of elemental changes is minimised.element_change (bool, default True) – If
True, allow elemental changes in mappings.seed (str | None, default None) – SMARTS string to use as seed for MCS searches. When used across an entire set of ligands, this can speed up calculations considerably. If
Nonean empty string (i.e. no seed) will be passed through.shift (bool, default True) – If
True, whenthreedis alsoTrue, translate the molecules’ coordinates to maximise 3D overlap.versionchanged: (..) – 2.1.0: Added element_change kwarg
versionchanged: – 2.2.0: Added seed option
versionchanged: – 2.3.0: Added shift option
- all_atom_match_list() str#
Gives a string listing the MCS match between the two molecules as atom_m1:atom_m2,atom_m1:atom_m2,…
All atoms including hydrogens. The string is sorted by first index. We need to be careful that this function is symmetric, and that hydrogens are mapped correctly.
- Returns:
Comma separated string of paired atom indices, sorted by the first index.
- Return type:
- atomic_number_rule() float#
This rule checks how many elements have been changed in the MCS and returns a score based on the fraction of MCS matches that are the same atomic number. When used with beta=0.1 and multiplied by mcsr, this is equivalent to counting mismatched atoms at only half weight.
This has been extended to modify the amount of mismatch according to the atoms being mapped.
- Returns:
an_score – Atomic number rule score.
- Return type:
- static getMapping(moli: Mol, molj: Mol, hydrogens: bool = False, fname: str | None = None, time_out: int = 150) Iterator[tuple[int, int]]#
Compute the MCS between two passed molecules
- Parameters:
moli (Chem.Mol) – The first molecule used to perform the MCS calculation.
molj (Chem.Mol) – The second molecule used to perform the MCS calculation.
hydrogens (bool, default False) – Include or not the hydrogens in the MCS calculation.
fname (str | None, default None) – The filename used to output a png file depicting the MCS mapping.
time_out (int, default 150) – The maximum time in seconds which can be used to compute the MCS.
- Returns:
map_moli_molj – Iterator of tuples which contains the atom mapping indexes between the two molecules. The indexes (i,j) are respectively related to the first (moli) and the second (molj) passed molecules.
- Return type:
- heavy_atom_match_list() str#
- Gives a string listing the MCS match between the two molecules as
atom_m1:atom_m2,atom_m1:atom_m2,…
Heavy atoms only.
- Returns:
Comma separated string of paired heavy atom indices.
- Return type:
- heavy_atom_mcs_map() list[tuple[int, int]]#
Gives a list of tuples mapping atoms from moli to molj Heavy atoms only, returned sorted by first index.
- heterocycles_rule(penalty: int = 4) float#
This rule checks to see if we are growing a heterocycle from a hydrogen, and returns <1 if we are. This means that if this rule is used we penalise this transition. Testing has shown that growing a pyridine or other heterocycle is unlikely to work (better to grow phenyl then mutate)
- hybridization_rule(penalty_weight: float = 1.5) float#
This rule checks how many atoms have changed hybridization state.
- Parameters:
penalty_weight (float, default 1.5) – How many “atoms” different a hybridization state change has. 1 means that the atom is effectively removed from the MCS for scoring purposes, 0 means that the hybridization changes are free. When used with
betaof0.1, and multiplied bymcsr, this is equivalent to counting mismatched atoms at a weight of(1 - penalty_weight).- Returns:
hyb_score – The hybridization rule score.
- Return type:
- mcsr() float#
This rule computes the similarity between the two passed molecules used to compute the MCS.
- Returns:
scr_mcsr – The MCSR rule score.
- Return type:
- mncar(ths: int = 4) float#
This rule cuts the similarity score between two molecules if they do not share the selected number of atoms.
- Parameters:
ths (int) – The minimum number of atoms to share.
- Returns:
scr_mncar – The MNCAR rule score.
- Return type:
Notes
This rule has been modified from the rule originally described in the Lomap paper so that it can match the first LOMAP implementation provided by Schrodinger.
- sulfonamides_rule(penalty: int = 4) float#
This rule checks to see if we are growing a complete sulfonamide, and returns 0 if we are. This means that if this rule is used we effectively disallow this transition. Testing has shown that growing -SO2NH2 from scratch performs very badly.
- tmcsr(strict_flag: bool = True) float#
TMCSR (Trim) rule. This score is no longer implemented and now always returns 1.0.
Notes
MDM - we don’t use this as we don’t have the same limitation on partial ring deletion as Schrodinger.
Removed the chirality check, the MCS is now trimmed to remove chirality.
- transmuting_methyl_into_ring_rule(penalty: int = 6) float#
Rule to prevent turning a methyl into a ring atom and similar transformations (you can grow a ring, but you can’t transmute into one).
- class lomap.graphgen.GraphGen(score_matrix: ndarray, ids: list[int], names: list[str], max_path_length: int, actives: list[bool], max_dist_from_active: int, similarity_cutoff: float, require_cycle_covering: bool, radial: bool, fast: bool, hub: str | None = None)#
This class is used to set and generate the graph used to plan binding free energy calculation.
Notes
To use the
GraphGendraw(),generate_depictions(), and_write_output_dot_graph()methods, you will need to install the optional dependencypygraphviz.- Parameters:
score_matrix (np.ndarray) – Array of scores between each molecule. Should be a symmetric (n x n) matrix.
ids (list[int]) – Indices for each molecule. Should be the same length as
score_matrix. These ids are used as the'ID'attribute in the resulting graph.names (list[str]) – List of string identifiers for each molecule. These names are used as the
'fname_comp'attribute in the resulting graph.max_path_length (int) – The maximum allowed shortest path length between any two molecules in the graph.
actives (list[bool]) – For each molecule in input, whether it is considered active. Used in conjunction with the
max_dist_from_activeargument.max_dist_from_active (int) – The maximum allowed shortest path length from any molecule to the nearest active molecule.
similarity_cutoff (float) – The value above which edges must be to be considered viable.
0.0would allow all edges.require_cycle_covering (bool) – If
True, enforce that every node is part of a cycle in the graph.radial (bool) – Whether to construct a radial graph. Note that this radial graph will still include cycles.
fast (bool) – If
True, use the faster radial-only algorithm (requiresradial=True).hub (str, optional) – The name of the molecule to use as the center of the hub.
- resultGraph#
The generated Lomap graph.
- Type:
nx.Graph
- add_surrounding_edges(subgraphs: list[Graph], score_matrix: ndarray, lead_index: int, similarity_score_limit: float) Graph#
Add surrounding edges in each subgraph to make sure all nodes are in cycle.
- Parameters:
subgraphs (list[nx.Graph]) – The list of subgraphs to add surrounding edges to.
score_matrix (np.ndarray) – Matrix of similarity scores between molecules.
lead_index (int) – The index of the lead (hub) molecule.
similarity_score_limit (float) – The minimum similarity score threshold for adding edges.
- Returns:
The subgraph containing the lead molecule, with surrounding edges added.
- Return type:
nx.Graph
- Raises:
ValueError – If the
lead_indexis not in any subgraph.
- check_constraints(subgraph: Graph, numComp: int, require_cycle_covering: bool) bool#
Determine if the given subgraph still meets the constraints.
- static check_cycle_covering(subgraph: Graph, non_cycle_edges_set: set[tuple[int, int]]) bool#
Checks if the subgraph has a cycle covering.
- Parameters:
- Returns:
hasCovering –
Trueif the subgraph has a cycle covering,Falseotherwise.- Return type:
Notes
This has been extended from the original algorithm. We not only care if the number of acyclic nodes has increased, but also if the number of acyclic edges (bridges) has increased. If the number of acyclic edges hasn’t increased, then the number of acyclic nodes hasn’t either, so that test is included in the edges test.
- check_distance_to_active(subgraph: Graph, distance_to_active_failures: int, max_distance_from_active: int) bool#
Check to see if we have increased the number of distance-to-active failures.
- Parameters:
- Returns:
ok –
Trueif the number of failed nodes has not increased.- Return type:
- static check_max_distance(subgraph: Graph, max_path_length: int) bool#
Check to see if the graph has paths from all molecules to all other molecules within the specified limit.
- connect_graph_components_brute_force() bool#
Adds edges to the resultGraph to connect all components that can be connected, only one edge is added per component, to form a tree like structure between the different components of the resultGraph.
- Returns:
Trueif there are edges that could have been added.- Return type:
- connect_graph_components_brute_force_2() bool#
Adds a second edge between each of the (former) components of the resultGraph to try to provide cycles between (former) components.
- Returns:
Trueif the addition of edges was possible.- Return type:
- connect_subgraphs() None#
Adds edges to the resultGraph to connect as many components of the final graph possible.
- static count_distance_to_active_failures(subgraph: Graph, max_dist_from_active: int) int#
Count the number of molecules that don’t have a minimum-length path to an active within the specified limit.
- Parameters:
subgraph (nx.Graph) – The subgraph to check for distance to active nodes.
max_dist_from_active (int) – The maximum allowed shortest path length from any molecule to the nearest active.
- Returns:
failures – Number of nodes that are not within
max_dist_from_activeto any active node.- Return type:
- draw(dbase: DBMolecules, max_images: int = 2000, max_nodes: int = 100, edge_labels: bool = True) None#
Plot the NetworkX graph using Matplotlib.
- Parameters:
dbase (DBMolecules) – The molecule database object.
max_images (int, default 2000) – Max number of displayed chemical molecule images as graph nodes.
max_nodes (int, default 100) – Max number of displayed nodes in the graph.
edge_labels (bool, default True) – If
True, add edge labels in the graph.
Notes
This requires the optional dependency
pygraphviz.
- generate_depictions(dbase: DBMolecules, max_images: int = 2000, max_mol_size: float = 50.0, edge_labels: bool = True) None#
Generate images of the network.
- Parameters:
dbase (DBMolecules) – The molecule database object.
max_images (int, default 2000) – Max number of displayed chemical molecule images as graph nodes.
max_mol_size (float, default 50.0) – The maximum threshold distance in angstroms used to select if a molecule is depicted.
edge_labels (bool, default True) – If
True, add labels on edges.
- static generate_initial_subgraph_list(fast_map: bool, strict_mtx: ndarray, ids: list[int], names: list[str], is_active: list[bool], lead_index: int | None) list[Graph]#
Generate a starting graph with edges connecting all the molecules with a positive strict similarity score.
- Parameters:
- Returns:
initialSubgraphList – The list of connected component graphs.
- Return type:
list[nx.Graph]
- Raises:
ValueError – If
lead_indexis not defined andfast_mapisTrue.
- static generate_subgraph_scores_lists(subgraphList: list[Graph]) list[list[tuple[int, int, float]]]#
This function generate a list of lists where each inner list is the weights of each edge in a given subgraph in the subgraphList, sorted from lowest to highest
- static generate_working_subgraphs_list(subgraph_list: list[Graph]) list[Graph]#
Generate a list of connected subgraphs.
This method is called after the deletion of the edges that have a weight less than the selected threshold. When this happens the subgraph maybe disconnected and so this method is called to create a new master list of connected subgraphs.
- layout_info(dbase: DBMolecules) None#
Write layout information (connectivity) and scoring data to text files.
- Parameters:
dbase (DBMolecules) – The molecule database object.
- static merge_all_subgraphs(working_subgraphs: list[Graph]) Graph#
Generates a single networkx graph object from the subgraphs that have been processed
- Parameters:
working_subgraphs (list[nx.Graph]) – The list of subgraphs to merge.
- Returns:
finalGraph – The final graph produced by merging all the subgraphs. The produced graph may have disconnected parts.
- Return type:
nx.Graph
- minimize_edges(require_cycle_covering: bool) None#
Minimize edges in each subgraph while ensuring constraints are met
- Parameters:
require_cycle_covering (bool) – If
True, enforce that every node is part of a cycle in the graph.
- static pick_lead(hub: str | None, names: list[str], strict_mtx: ndarray) int | None#
Pick a lead molecule.
- static remains_connected(subgraph: Graph, numComponents: int) bool#
Determine if the subgraph remains connected after an edge has been removed.
- static remove_edges_below_hard_limit(subgraphlist: list[Graph], scores: list[list[tuple[int, int, float]]], similarity_scores_limit: float) None#
Remove edges below the set hard limit from each subGraph and from each weightsList.
Operates on subgraphlist in-place!
- write_graph(dbase: DBMolecules, output_no_images: bool, output_no_graph: bool) None#
Write the final generated NetworkX graph as
.dotand the.psfiles. The mapping between molecule IDs and molecules name is saved as text file.- Parameters:
dbase (DBMolecules) – The molecule database object.
output_no_images (bool) – If
True, do not generate image files.output_no_graph (bool) – If
True, do not generate the dot graph file.
- Raises:
OSError – If database or image writing fails.