Coverage for SynRBL/SynMCSImputer/rules.py: 91%
398 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
1from __future__ import annotations
3import json
4import inspect
5import numpy as np
6import importlib.resources
7import rdkit.Chem as Chem
8import rdkit.Chem.rdmolfiles as rdmolfiles
9import rdkit.Chem.rdmolops as rdmolops
10import rdkit.Chem.rdchem as rdchem
12import SynRBL.SynMCSImputer
13import SynRBL.SynUtils.functional_group_utils as fgutils
14import SynRBL.SynMCSImputer.utils as utils
16from SynRBL.SynUtils.chem_utils import remove_atom_mapping
17from .structure import Boundary, Compound
20def _check_config(init, ignore=[], **kwargs):
21 exp_args = inspect.getfullargspec(init)[0]
22 for k in kwargs.keys():
23 if k in ignore:
24 continue
25 if k not in exp_args:
26 raise KeyError(
27 "Parameter '{}' is not valid for '{}'.".format(k, init.__name__)
28 )
31def parse_bond_type(bond):
32 """
33 Convert bond name into the correct rdkit type.
35 Arguments:
36 bond (str): Bond type name. E.g.: single, double
38 Returns:
39 rdkit.Chem.rdchem.BondType: The rdkit bond type.
40 """
41 if bond is None:
42 return None, 0
43 elif bond == "single":
44 return Chem.rdchem.BondType.SINGLE, 1
45 elif bond == "double":
46 return Chem.rdchem.BondType.DOUBLE, 2
47 else:
48 raise NotImplementedError("Bond type '{}' is not implemented.".format(bond))
51class Property:
52 """
53 Generic property for dynamic rule configuration.
55 Attributes:
56 neg_values (list): List of forbidden values. Forbidden value check is
57 skipped if this list is empty.
58 pos_values (list): List of valid values. If this list is empty, all
59 values are excepted.
60 allow_none (bool): If a value of None is allowed and checked as valid.
61 """
63 def __init__(
64 self,
65 config: str | list[str] | None = None,
66 allow_none=False,
67 ):
68 """
69 Generic property for dynamic rule configuration.
71 Arguments:
72 config (str | list[str]): Configuration for this property. This is
73 a list of acceptable and forbiden values.
74 e.g.: ['A', 'B'] -> check is true if value is A or B
75 ['!C', '!D'] -> check is true if value is not C and not D
76 allow_none (bool): Flag if a check with value None is valid or not.
77 """
78 self.allow_none = allow_none
79 self.neg_values = []
80 self.pos_values = []
81 if config is not None:
82 # type bool or int
83 if isinstance(config, bool) or isinstance(config, int):
84 self.pos_values.append(config)
85 # type str
86 else:
87 if not isinstance(config, list):
88 config = [config]
89 for item in config:
90 if not isinstance(item, str):
91 raise ValueError(
92 "Property configuration must be of type str or list[str]."
93 )
94 if len(item) > 0 and item[0] == "!":
95 self.neg_values.append(item[1:])
96 else:
97 self.pos_values.append(item)
99 def check(self, value, check_value) -> bool:
100 return value == check_value
102 def __call__(self, value) -> bool:
103 """
104 Check if the property is true for the given value.
106 Arguments:
107 value: The value to check. It must be of the same datatype as
108 specified in the constructor.
110 Returns:
111 bool: True if the value fulfills the property, false otherwise.
112 """
113 if value is None:
114 if self.allow_none:
115 return True
116 else:
117 raise ValueError(
118 "Passed value None to property that does not allow None."
119 )
120 if len(self.pos_values) > 0:
121 found = False
122 for pv in self.pos_values:
123 r = self.check(value, pv)
124 # print("{} pos. check return {}.".format(self.__class__.__name__, r))
125 if r:
126 found = True
127 break
128 if not found:
129 return False
130 if len(self.neg_values) > 0:
131 for nv in self.neg_values:
132 r = self.check(value, nv)
133 # print("{} neg. check return {}.".format(self.__class__.__name__, r))
134 if r:
135 return False
136 return True
139class CompoundProperty(Property):
140 def __init__(self, config=None, allow_none=False):
141 super().__init__(config, allow_none)
143 def __call__(self, value) -> bool:
144 if not isinstance(value, Compound):
145 raise TypeError(
146 "Compound property can only be called with a compound as argument."
147 )
148 return super().__call__(value)
151class Action:
152 __actions = {}
154 @classmethod
155 def build(cls, name, **kwargs) -> Action:
156 if name not in cls.__actions.keys():
157 raise NotImplementedError("No action named '{}' found.".format(name))
158 inst = cls.__actions[name](**kwargs)
159 return inst
161 @classmethod
162 def register(cls, name: str, action):
163 if name in cls.__actions.keys():
164 raise ValueError("Action with name '{}' already exists.".format(name))
165 cls.__actions[name] = action
167 def apply(self, boundary: Boundary):
168 pass
170 def __call__(self, boundary: Boundary):
171 self.apply(boundary)
174class ChangeBondAction(Action):
175 def __init__(self, pattern=None, bond=None, **kwargs):
176 _check_config(ChangeBondAction, ignore=["type"], **kwargs)
177 pattern = kwargs.get("pattern", pattern)
178 bond = kwargs.get("bond", bond)
180 if pattern is None:
181 raise ValueError("Missing required parameter 'pattern'.")
183 if bond is None:
184 raise ValueError("Missing required parameter 'bond'.")
186 self.pattern_mol = rdmolfiles.MolFromSmiles(pattern)
187 self.bond_type, _ = parse_bond_type(bond)
189 if (
190 len(self.pattern_mol.GetAtoms()) != 2
191 or len(self.pattern_mol.GetBonds()) != 1
192 ):
193 raise ValueError(
194 "Pattern for change_bond action must be a smiles with 2 "
195 + "atoms and 1 bond. "
196 + "Value '{}' is invalid.".format(pattern)
197 )
199 def apply(self, boundary: Boundary):
200 match, mapping = fgutils.pattern_match(
201 boundary.compound.mol, boundary.index, self.pattern_mol
202 )
203 assert match, (
204 "No match found for pattern '{}' in '{}' @ {}. "
205 + "Fix the condition in the rule configuration."
206 ).format(
207 rdmolfiles.MolToSmiles(self.pattern_mol),
208 boundary.compound.smiles,
209 boundary.index,
210 )
211 emol = rdchem.EditableMol(boundary.compound.mol)
212 emol.RemoveBond(mapping[0][0], mapping[1][0])
213 emol.AddBond(mapping[0][0], mapping[1][0], self.bond_type)
214 boundary.compound.mol = emol.GetMol()
217Action.register("change_bond", ChangeBondAction)
220class CompoundAction:
221 __actions = {}
223 @classmethod
224 def build(cls, name, **kwargs) -> CompoundAction:
225 if name not in cls.__actions.keys():
226 raise NotImplementedError(
227 "No compound action named '{}' found.".format(name)
228 )
229 inst = cls.__actions[name](**kwargs)
230 return inst
232 @classmethod
233 def register(cls, name: str, action):
234 if name in cls.__actions.keys():
235 raise ValueError(
236 "Compound action with name '{}' already exists.".format(name)
237 )
238 cls.__actions[name] = action
240 def apply(self, compound: Compound):
241 pass
243 def __call__(self, compound: Compound) -> Compound | None:
244 self.apply(compound)
247class AddBoundaryAction(CompoundAction):
248 def __init__(self, functional_group=None, pattern=None, index=None, **kwargs):
249 _check_config(AddBoundaryAction, ignore=["type"], **kwargs)
250 functional_group = kwargs.get("functional_group", functional_group)
251 pattern = kwargs.get("pattern", pattern)
252 index = kwargs.get("index", index)
254 if pattern is None:
255 raise ValueError("Missing required parameter 'pattern'.")
257 if index is None:
258 raise ValueError("Missing required parameter 'index'.")
260 self.functional_group = functional_group
261 self.pattern_mol = rdmolfiles.MolFromSmiles(pattern)
262 self.index = int(index)
264 if len(self.pattern_mol.GetAtoms()) <= self.index:
265 raise ValueError(
266 "Index for pattern in add_boundary action is out of range."
267 )
269 def apply(self, compound: Compound):
270 for atom in compound.mol.GetAtoms():
271 if atom.GetSymbol() in ["C", "H"]:
272 continue
273 atom_index = atom.GetIdx()
274 if self.functional_group is not None:
275 is_fg = fgutils.is_functional_group(
276 compound.mol, self.functional_group, atom_index
277 )
278 if not is_fg:
279 continue
280 match, mapping = fgutils.pattern_match(
281 compound.mol, atom_index, self.pattern_mol, self.index
282 )
283 if match:
284 for m in mapping:
285 if m[1] == self.index:
286 compound.add_boundary(m[0])
287 return
288 raise RuntimeError("Action add_boundary could not be applied.")
291class SetActiveAction(CompoundAction):
292 def __init__(self, active=None, **kwargs):
293 _check_config(SetActiveAction, ignore=["type"], **kwargs)
294 self.active = bool(kwargs.get("active", active))
296 def apply(self, compound: Compound):
297 compound.active = self.active
300CompoundAction.register("add_boundary", AddBoundaryAction)
301CompoundAction.register("set_active", SetActiveAction)
304class FunctionalGroupProperty(Property):
305 def __init__(self, config=None):
306 super().__init__(config, allow_none=False)
308 def check(self, value: Boundary, check_value) -> bool:
309 if value.compound.src_mol is not None and value.neighbor_index is not None:
310 src_mol = value.promise_src()
311 neighbor_index = value.promise_neighbor_index()
312 return fgutils.is_functional_group(src_mol, check_value, neighbor_index)
313 else:
314 return False
317class PatternProperty(Property):
318 def __init__(self, config=None, use_src_mol: bool = False):
319 super().__init__(config, allow_none=False)
320 self.use_src_mol = use_src_mol
322 def check(self, boundary: Boundary, value) -> bool:
323 pattern_mol = rdmolfiles.MolFromSmiles(value)
324 mol = boundary.compound.mol
325 index = boundary.index
326 if self.use_src_mol:
327 mol = boundary.promise_src()
328 index = boundary.promise_neighbor_index()
329 match, _ = fgutils.pattern_match(
330 mol,
331 index,
332 pattern_mol,
333 )
334 return match
337class BoundarySymbolProperty(Property):
338 def __init__(self, config=None):
339 super().__init__(config, allow_none=False)
341 def check(self, value: Boundary, check_value) -> bool:
342 return value.symbol == check_value
345class NeighborSymbolProperty(Property):
346 def __init__(self, config=None):
347 super().__init__(config, allow_none=False)
349 def check(self, value: Boundary, check_value) -> bool:
350 return value.neighbor_symbol == check_value
353class CountBoundariesCompoundProperty(CompoundProperty):
354 def __init__(self, config=None, use_set=False):
355 super().__init__(config, allow_none=False)
356 self.use_set = use_set
358 def check(self, value: Compound, check_value) -> bool:
359 value_l = len(value.boundaries)
360 if self.use_set:
361 value_l = len(value.compound_set.boundaries)
362 return value_l == int(check_value)
365class CountCompoundsCompoundProperty(CompoundProperty):
366 def __init__(self, config=None, compound_type=None):
367 super().__init__(config, allow_none=False)
368 self.compound_type = compound_type
370 def check(self, value: Compound, check_value) -> bool:
371 compounds = value.compound_set.compounds
372 if self.compound_type == "open":
373 compounds = [c for c in compounds if not c.is_catalyst]
374 elif self.compound_type == "catalyst":
375 compounds = [c for c in compounds if c.is_catalyst]
376 return len(compounds) == int(check_value)
379class IsCatalystCompoundProperty(CompoundProperty):
380 def __init__(self, config=None):
381 super().__init__(config, allow_none=False)
383 def check(self, value: Compound, check_value) -> bool:
384 return value.is_catalyst == bool(check_value)
387class FunctionalGroupCompoundProperty(CompoundProperty):
388 def __init__(self, config=None):
389 super().__init__(config, allow_none=False)
391 def check(self, value: Compound, check_value) -> bool:
392 for atom in value.mol.GetAtoms():
393 idx = atom.GetIdx()
394 if atom.GetSymbol() not in ["H", "C"]:
395 is_fg = fgutils.is_functional_group(value.mol, check_value, idx)
396 if is_fg:
397 return True
398 return False
401class SmilesCompoundProperty(CompoundProperty):
402 def __init__(self, config=None, use_src_mol: bool = False):
403 super().__init__(config, allow_none=False)
404 self.use_src_mol = use_src_mol
406 def check(self, value: Compound, check_value) -> bool:
407 if self.use_src_mol:
408 if value.src_smiles is not None:
409 return remove_atom_mapping(value.src_smiles) == check_value
410 return value.src_smiles == check_value
411 else:
412 return remove_atom_mapping(value.smiles) == check_value
415class BoundaryCondition:
416 """
417 Atom condition class to check if a rule is applicable to a specific
418 molecule. Property configs can be prefixed with '!' to negate the check.
419 See SynRBL.SynMCSImputer.rule_formation.Property for more information.
421 Example:
422 Check if atom is Carbon and has Oxygen or Nitrogen as neighbor.
423 >>> cond = AtomCondition(atom=['C'], neighbors=['O', 'N'])
424 >>> mol = rdkit.Chem.rdmolfiles.MolFromSmiles('CO')
425 >>> cond.check(mol.GetAtomFromIdx(0), neighbor='O')
426 True
428 Attributes:
429 atom (SynRBL.SynMCSImputer.rule_formation.Property): Atom property
430 neighbor_atom (SynRBL.SynMCSImputer.rule_formation.Property): Neighbors property
431 """
433 def __init__(
434 self,
435 atom=None,
436 neighbor_atom=None,
437 functional_group=None,
438 pattern=None,
439 src_pattern=None,
440 **kwargs,
441 ):
442 """
443 Atom condition class to check if a rule is applicable to a specific
444 molecule. Property configs can be prefixed with '!' to negate the
445 check. See SynRBL.SynMCSImputer.rule_formation.Property for more information.
447 Arguments:
448 atom: Atom property configuration.
449 neighbor: Neighbor property configuration.
450 functional_groups: Functional group property configuration.
451 """
452 _check_config(BoundaryCondition, **kwargs)
453 atom = kwargs.get("atom", atom)
454 neighbor_atom = kwargs.get("neighbor_atom", neighbor_atom)
455 functional_group = kwargs.get("functional_group", functional_group)
456 pattern = kwargs.get("pattern", pattern)
457 src_pattern = kwargs.get("src_pattern", src_pattern)
459 self.properties = [
460 BoundarySymbolProperty(atom),
461 NeighborSymbolProperty(neighbor_atom),
462 FunctionalGroupProperty(functional_group),
463 PatternProperty(pattern),
464 PatternProperty(src_pattern, use_src_mol=True),
465 ]
467 def __call__(self, boundary: Boundary):
468 """
469 Check if the boundary meets the condition.
471 Arguments:
472 boundary (SynRBS.SynMCS.structure.Boundary): Boundary the
473 condition should be checked for.
475 Returns:
476 bool: True if the boundary fulfills the condition, false otherwise.
477 """
478 for prop in self.properties:
479 if not prop(boundary):
480 return False
481 return True
484class CompoundCondition:
485 def __init__(
486 self,
487 nr_boundaries=None,
488 is_catalyst=None,
489 smiles=None,
490 functional_group=None,
491 **kwargs,
492 ):
493 _check_config(CompoundCondition, **kwargs)
494 nr_boundaries = kwargs.get("nr_boundaries", nr_boundaries)
495 is_catalyst = kwargs.get("is_catalyst", is_catalyst)
496 smiles = kwargs.get("smiles", smiles)
497 functional_group = kwargs.get("functional_group", functional_group)
499 self.properties = [
500 CountBoundariesCompoundProperty(nr_boundaries),
501 IsCatalystCompoundProperty(is_catalyst),
502 SmilesCompoundProperty(smiles),
503 FunctionalGroupCompoundProperty(functional_group),
504 ]
506 def __call__(self, compound: Compound):
507 for prop in self.properties:
508 if not prop(compound):
509 return False
510 return True
513class SetCondition:
514 def __init__(self, nr_boundaries=None, nr_compounds=None, **kwargs):
515 _check_config(SetCondition, **kwargs)
516 nr_boundaries = kwargs.get("nr_boundaries", nr_boundaries)
517 nr_compounds = kwargs.get("nr_compounds", nr_compounds)
519 self.properties = [
520 CountBoundariesCompoundProperty(nr_boundaries, use_set=True),
521 CountCompoundsCompoundProperty(nr_compounds),
522 ]
524 def __call__(self, compound: Compound):
525 for prop in self.properties:
526 if not prop(compound):
527 return False
528 return True
531class CompoundRuleCondition:
532 def __init__(self, compound={}, set={}, **kwargs):
533 _check_config(CompoundRuleCondition, **kwargs)
534 compound_condition = kwargs.get("compound", compound)
535 set_condition = kwargs.get("set", set)
537 self.compound_condition = CompoundCondition(**compound_condition)
538 self.set_condition = SetCondition(**set_condition)
540 def __call__(self, compound: Compound) -> bool:
541 return self.compound_condition(compound) and self.set_condition(compound)
544class NoMergeRuleError(Exception):
545 """
546 Exception if no merge rule is found to combine two molecules.
547 """
549 def __init__(self, boundary_atom1, boundary_atom2, mol1, mol2):
550 """
551 Exception when no merge rule is found to combine two molecules.
553 Arguments:
554 boundary_atom1 (str): Atom symbol of first boundary atom.
555 boundary_atom2 (str): Atom symbol of second boundary atom.
556 mol1 (rdkit.Chem.Mol): Part one of molecule to be merged.
557 mol2 (rdkit.Chem.Mol): Part two of molecule to be merged.
558 """
559 super().__init__(
560 (
561 "Not able to find merge rule for atoms '{}' and "
562 + "'{}' of compounds '{}' and '{}'."
563 ).format(
564 boundary_atom1.GetSymbol(),
565 boundary_atom2.GetSymbol(),
566 rdmolfiles.MolToSmiles(rdmolops.RemoveHs(mol1)),
567 rdmolfiles.MolToSmiles(rdmolops.RemoveHs(mol2)),
568 )
569 )
572class MergeError(Exception):
573 """
574 Exception if merge failed.
575 """
577 def __init__(self, rule_name, inner_msg=None):
578 """
579 Exception if merge failed.
580 """
582 msg = "Merge rule '{}' failed.".format(rule_name)
583 if inner_msg is not None:
584 msg += " {}".format(inner_msg)
585 super().__init__(msg)
588class MergeRule:
589 """
590 Class for defining a merge rule between two compounds. If boundary atom1
591 meets condition1 and boundary atom2 meets condition2 a bond is formed
592 between atom1 and atom2. A merge rule can be configured by providing a
593 suitable dictionary. Examples on how to configure merge rules can be found
594 in SynRBL/SynMCS/merge_rules.json file.
596 Example:
597 The following example shows a complete default configuration for a merge rule.
598 config = {
599 "name": "unnamed",
600 "condition1": {
601 "atom": None,
602 "neighbors": None,
603 },
604 "condition2": {
605 "atom": None,
606 "neighbors": None,
607 },
608 "bond": None,
609 "sym": True
610 }
611 rule = MergeRule(**config)
613 Attributes:
614 name (str, optional): A descriptive name for the rule. This attribute
615 is just for readability and does not serve a functional purpose.
616 condition1 (AtomCondition, optional): Condition
617 for the first boundary atom.
618 condition2 (AtomCondition, optional): Condition
619 for the second boundary atom.
620 bond (str, optional): The bond type to form between the two compounds.
621 """
623 _merge_rules: list[MergeRule] | None = None
625 def __init__(
626 self,
627 name="unnamed",
628 condition1={},
629 condition2={},
630 action1=[],
631 action2=[],
632 bond=None,
633 **kwargs,
634 ):
635 _check_config(MergeRule, **kwargs)
636 self.name = kwargs.get("name", name)
637 self.condition1 = BoundaryCondition(**kwargs.get("condition1", condition1))
638 self.condition2 = BoundaryCondition(**kwargs.get("condition2", condition2))
640 actions1 = kwargs.get("action1", action1)
641 actions2 = kwargs.get("action2", action2)
642 if not isinstance(actions1, list):
643 actions1 = [actions1]
644 if not isinstance(actions2, list):
645 actions2 = [actions2]
647 self.action1 = [Action.build(a["type"], **a) for a in actions1]
648 self.action2 = [Action.build(a["type"], **a) for a in actions2]
649 self.bond = kwargs.get("bond", bond)
651 @classmethod
652 def get_all(cls) -> list[MergeRule]:
653 """
654 Get a list of merge rules. The rules are configured in
655 SynRBL/SynMCS/merge_rules.json.
657 Returns:
658 list[MergeRule]: Returns a list of merge rules.
659 """
660 if cls._merge_rules is None:
661 json_data = (
662 importlib.resources.files(SynRBL.SynMCSImputer)
663 .joinpath("merge_rules.json")
664 .read_text()
665 )
666 cls._merge_rules = [MergeRule(**c) for c in json.loads(json_data)]
667 return cls._merge_rules
669 def can_apply(self, boundary1: Boundary, boundary2: Boundary):
670 """
671 Check if the rule can be applied to merge atom1 and atom2.
673 Arguments:
674 boundary1 (SynRBL.SynMCSImputer.structure.Boundary): First boundary.
675 boundary2 (SynRBL.SynMCSImputer.structure.Boundary): Second boundary.
677 Returns:
678 bool: True if the rule can be applied, false otherwise.
679 """
680 return (self.condition1(boundary1) and self.condition2(boundary2)) or (
681 self.condition1(boundary2) and self.condition2(boundary1)
682 )
684 def apply(self, boundary1: Boundary, boundary2: Boundary) -> Compound | None:
685 def _fix_Hs(atom, bond_nr):
686 if atom.GetNumExplicitHs() > 0:
687 atom.SetNumExplicitHs(
688 int(np.max([0, atom.GetNumExplicitHs() - bond_nr]))
689 )
691 if not (self.condition1(boundary1) and self.condition2(boundary2)):
692 boundary1, boundary2 = boundary2, boundary1
693 assert self.condition1(boundary1) and self.condition2(
694 boundary2
695 ), "Rule can not be applied."
697 for a in self.action1:
698 a(boundary1)
699 for a in self.action2:
700 a(boundary2)
702 bond_type, bond_nr = parse_bond_type(self.bond)
703 if bond_type is not None:
704 _fix_Hs(boundary1.get_atom(), bond_nr)
705 _fix_Hs(boundary2.get_atom(), bond_nr)
707 merge_result = utils.merge_two_mols(
708 boundary1.compound.mol,
709 boundary2.compound.mol,
710 boundary1.index,
711 boundary2.index,
712 bond_type,
713 )
715 mol = merge_result["mol"]
716 rdmolops.SanitizeMol(mol)
718 boundary1.compound.update(mol, boundary1)
719 boundary1.compound.rules.extend(boundary2.compound.rules)
720 boundary1.compound.rules.append(self)
721 return boundary1.compound
724class ExpandRule:
725 """
726 Class for defining a compound expansion rule. The compound is added if the
727 boundary atom meets the condition. A compound rule can be configured by
728 providing a suitable dictionary. Examples on how to configure compound
729 rules can be found in SynRBL/SynMCS/expand_rules.json file.
731 Attributes:
732 name (str, optional): A descriptive name for the rule. This attribute
733 is just for readability and does not serve a functional purpose.
734 condition (AtomCondition, optional): Condition
735 for the boundary atom.
736 compound (dict): The compound to add as dictionary in the following
737 form: {'smiles': <SMILES>, 'index': <boundary atom index>}.
738 """
740 _expand_rules: list[ExpandRule] | None = None
742 def __init__(self, name="unnamed", condition={}, compound=None, **kwargs):
743 _check_config(ExpandRule, **kwargs)
744 self.name = kwargs.get("name", name)
745 self.condition = BoundaryCondition(**kwargs.get("condition", condition))
746 self.compound = kwargs.get("compound", compound)
748 @classmethod
749 def get_all(cls) -> list[ExpandRule]:
750 """
751 Get a list of compound expansion rules. The rules are configured in
752 SynRBL/SynMCS/expand.json.
754 Returns:
755 list[ExpandRule]: Returns a list of compound rules.
756 """
757 if cls._expand_rules is None:
758 json_data = (
759 importlib.resources.files(SynRBL.SynMCSImputer)
760 .joinpath("expand_rules.json")
761 .read_text()
762 )
763 cls._expand_rules = [ExpandRule(**c) for c in json.loads(json_data)]
764 return cls._expand_rules
766 def can_apply(self, boundary: Boundary):
767 """
768 Checks if the compound rule can be applied to the atom.
770 Arguments:
771 atom (rdkit.Chem.Atom): The boundary atom which is checked for the
772 compound expansion.
773 neighbor (str): The neighboring atom to the boundary. This
774 additional information is required to find the correct
775 compound.
777 Returns:
778 bool: True if the compound rule can be applied, false otherwise.
779 """
780 return self.condition(boundary)
782 def apply(self) -> Compound:
783 """
784 Apply the compound rule.
786 Returns:
787 SynRBL.SynMCSImputer.structure.Compound: The compound generated by this
788 rule.
789 """
790 compound = Compound(self.compound["smiles"])
791 compound.add_boundary(self.compound["index"])
792 compound.rules.append(self)
793 return compound
796class CompoundRule:
797 _compound_rules: list[CompoundRule] | None = None
799 def __init__(self, name="unnamed", condition={}, action=[], **kwargs):
800 _check_config(CompoundRule, **kwargs)
802 action = kwargs.get("action", action)
803 if not isinstance(action, list):
804 action = [action]
805 condition = kwargs.get("condition", condition)
807 self.name = kwargs.get("name", name)
808 self.condition = CompoundRuleCondition(**condition)
809 self.action = [CompoundAction.build(a["type"], **a) for a in action]
811 @classmethod
812 def get_all(cls) -> list[CompoundRule]:
813 if cls._compound_rules is None:
814 json_data = (
815 importlib.resources.files(SynRBL.SynMCSImputer)
816 .joinpath("compound_rules.json")
817 .read_text()
818 )
819 cls._compound_rules = [CompoundRule(**c) for c in json.loads(json_data)]
820 return cls._compound_rules
822 def can_apply(self, compound: Compound):
823 return self.condition(compound)
825 def apply(self, compound: Compound) -> Compound:
826 for action in self.action:
827 action(compound)
828 compound.rules.append(self)
829 return compound
832def get_merge_rules() -> list[MergeRule]:
833 """
834 Get a list of merge rules. The rules are configured in
835 SynRBL/SynMCS/merge_rules.json.
837 Returns:
838 list[MergeRule]: Returns a list of merge rules.
839 """
840 return MergeRule.get_all()
843def get_expand_rules() -> list[ExpandRule]:
844 """
845 Get a list of compound expandsion rules. The rules are configured in
846 SynRBL/SynMCS/expand_rules.json.
848 Returns:
849 list[ExpandRule]: Returns a list of compound rules.
850 """
851 return ExpandRule.get_all()
854def get_compound_rules() -> list[CompoundRule]:
855 return CompoundRule.get_all()