vibe-sketcherDocumentation

Source code for vibesketcher.chem.query_worker

"""Isolated SMARTS parser/matcher; invoked only by document.queries (#167)."""

from __future__ import annotations

import json
import sys
from typing import Any


[docs] def match(payload: dict[str, Any]) -> dict[str, Any]: from rdkit import Chem, rdBase from vibesketcher import __version__ from vibesketcher.chem._rdkit import untyped from vibesketcher.chem.species import mol_from_smiles, without_hydrogens from vibesketcher.document.ket import read_scene, stereo_reason from vibesketcher.document.queries import ( MAX_ATOMS, MAX_FRAGMENTS, MAX_MATCHES, MAX_QUERY_ATOMS, AtomQuery, ) chem = untyped(Chem) spec = AtomQuery.model_validate(payload["query"]) pattern = None if spec.smarts is not None: pattern = chem.MolFromSmarts(spec.smarts) if pattern is None: raise ValueError("Invalid SMARTS") if "$(" in chem.MolToSmarts(pattern): raise ValueError("recursive SMARTS are unsupported; use explicit atom/bond patterns") if not 1 <= pattern.GetNumAtoms() <= MAX_QUERY_ATOMS: raise ValueError(f"SMARTS must contain 1 to {MAX_QUERY_ATOMS} query atoms") quiet = rdBase.BlockLogs() canvas = payload["canvas"] refs = [node["$ref"] for node in canvas.get("root", {}).get("nodes", []) if "$ref" in node] if len(refs) != len(set(refs)): raise ValueError("Repeated KET node references have ambiguous drawn identities") scene = read_scene(canvas) if len(scene.fragments) > MAX_FRAGMENTS: raise ValueError(f"atom queries support at most {MAX_FRAGMENTS} drawn fragments") by_smiles: dict[str, list[str]] = {} warnings: list[dict[str, Any]] = [] for item in payload["species"]: if item["smiles"]: try: key = str(chem.MolToSmiles(without_hydrogens(mol_from_smiles(item["smiles"])))) by_smiles.setdefault(key, []).append(item["id"]) except (ValueError, RuntimeError): warnings.append( {"species": item["id"], "reason": "stored species graph is invalid"} ) params = chem.SubstructMatchParameters() params.useChirality = spec.use_chirality params.useEnhancedStereo = spec.use_chirality params.uniquify = True params.numThreads = 1 params.maxRecursiveMatches = MAX_MATCHES + 1 matches: list[dict[str, Any]] = [] atoms: dict[tuple[str, int], dict[str, Any]] = {} targets = 0 drawn_species: set[str] = set() for occurrence, fragment in enumerate(scene.fragments): reason = fragment.unsupported or stereo_reason(canvas.get(fragment.node, {})) if fragment.mol is None or reason: warnings.append({"node": fragment.node, "reason": reason or "unsupported drawing"}) continue mol = fragment.mol targets += int(mol.GetNumAtoms()) if targets > MAX_ATOMS: raise ValueError(f"atom queries support at most {MAX_ATOMS} target atoms") key = str(chem.MolToSmiles(without_hydrogens(mol))) species = by_smiles.get(key, []) if not species: warnings.append( {"node": fragment.node, "reason": "drawn graph has no registered species ID"} ) drawn_species.update(species) if spec.species is not None and not set(species).intersection(spec.species): continue if pattern is not None: # RDKit's VF2 matcher: Cordella et al., IEEE TPAMI 26, # 1367-1372 (2004), doi:10.1109/TPAMI.2004.75. params.maxMatches = MAX_MATCHES + 1 - len(matches) hits = mol.GetSubstructMatches(pattern, params) if len(hits) >= params.maxMatches: raise ValueError(f"query exceeds {MAX_MATCHES} matches; narrow the query") else: assert spec.filter is not None f = spec.filter hits = [ (a.GetIdx(),) for a in mol.GetAtoms() if (f.elements is None or a.GetSymbol() in f.elements) and (f.charge is None or a.GetFormalCharge() == f.charge) and (f.aromatic is None or a.GetIsAromatic() == f.aromatic) and (f.in_ring is None or a.IsInRing() == f.in_ring) ] seen: set[tuple[int, ...]] = set() for hit in hits: indices = tuple(sorted(int(i) for i in hit)) if indices in seen: continue seen.add(indices) found = [] for index in indices: ref = (fragment.node, fragment.atoms[index]) if ref not in atoms: atoms[ref] = { "node": ref[0], "atom": ref[1], "element": mol.GetAtomWithIdx(index).GetSymbol(), } found.append(atoms[ref]) matches.append({"species": species, "occurrence": occurrence, "atoms": found}) if len(matches) > MAX_MATCHES: raise ValueError(f"query exceeds {MAX_MATCHES} matches; narrow the query") if spec.species is not None: for missing in sorted(set(spec.species) - drawn_species): warnings.append({"species": missing, "reason": "no supported drawn occurrence"}) del quiet return { "software": {"vibesketcher": __version__, "rdkit": rdBase.rdkitVersion}, "policy": { "aromaticity": "RDKit default via the KET bridge", "hydrogens": "drawn H atoms only; implicit H is a count predicate", "stereo": "RDKit chirality and enhanced stereo" if spec.use_chirality else "ignored", "deduplication": "identical atom sets within one drawn occurrence", "recursive_smarts": "unsupported to avoid silent recursive-match truncation", }, "counts": {"matches": len(matches), "atoms": len(atoms), "fragments": len(scene.fragments)}, "matches": matches, "atoms": list(atoms.values()), "warnings": warnings, }
[docs] def main() -> None: from vibesketcher.document.queries import MAX_RESULT_BYTES from vibesketcher.limits import MAX_INPUT_BYTES try: raw = sys.stdin.buffer.read(MAX_INPUT_BYTES + 1) if len(raw) > MAX_INPUT_BYTES: raise ValueError("query input exceeds the input size limit") result = match(json.loads(raw)) output = json.dumps(result, ensure_ascii=False, allow_nan=False).encode() if len(output) > MAX_RESULT_BYTES: raise ValueError("query exceeds the 8 MiB result limit; narrow the query") except (ValueError, RuntimeError, KeyError, TypeError, IndexError) as error: output = json.dumps({"error": str(error)[:1500]}).encode() sys.stdout.buffer.write(output)
if __name__ == "__main__": main()