vibe-sketcherDocumentation
Source code for vibesketcher.document.transfer
"""Read-only transfer of exactly one selected, complete canvas molecule."""
from __future__ import annotations
import json
from dataclasses import dataclass
from pydantic import BaseModel, ConfigDict, Field, StrictInt
from vibesketcher.document.model import Document
[docs]
class TransferRefused(ValueError):
"""The selection cannot be transferred without guessing its meaning."""
[docs]
class SelectedAtom(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
node: str = Field(min_length=1, max_length=200)
atom: StrictInt = Field(ge=0)
[docs]
class TransferSelection(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
atoms: list[SelectedAtom] = Field(min_length=1, max_length=500)
generate: bool = False
[docs]
def prepare_transfer(document: Document, selection: TransferSelection) -> StructureTransfer:
"""Export a complete selected molecule as QVF without editing ``document``.
References belong to this exact document's KET atom slots. Partial and
multiple fragments are refused, including two copies of the same species.
Generating a missing conformer requires explicit ``generate=True``.
"""
from vibesketcher.chem.species import identity
from vibesketcher.document.embed import embed
from vibesketcher.document.ket import read_scene
from vibesketcher.document.qvf import species_qvf
if len(json.dumps(document.canvas.data).encode()) > 4 * 2**20:
raise TransferRefused("Transfer supports drawings up to 4 MiB.")
wanted = {(a.node, a.atom) for a in selection.atoms}
if len(wanted) != len(selection.atoms):
raise TransferRefused("Select distinct drawn atoms.")
matches = [
f
for f in read_scene(document.canvas.data or {}).fragments
if {(f.node, a) for a in f.atoms} == wanted
]
if len(matches) != 1:
raise TransferRefused("Select exactly one complete connected molecule.")
fragment = matches[0]
if fragment.mol is None:
raise TransferRefused(fragment.unsupported or "This drawing is not a molecular structure.")
found = identity(fragment.mol)
species = [s for s in document.species if s.smiles == found.smiles and s.charge == found.charge]
if len(species) != 1:
raise TransferRefused("The selected molecule has no unambiguous stored species.")
selected = species[0]
generated = not bool(selected.conformers)
if generated and not selection.generate:
raise TransferRefused("Generate a 3D conformer for this transfer, or generate one first.")
prepared = document
if generated:
prepared, report = embed(document, [selected.id])
if report.failed:
raise TransferRefused(report.failed[selected.id])
return StructureTransfer(species_qvf(prepared, selected.id), selected.id, generated)
[docs]
def import_transfer(document: Document, data: bytes) -> tuple[Document, list[str]]:
"""Append one viewer geometry, refusing changed connectivity or identity warnings."""
import io
from vibesketcher.chem.perceive import perceive
from vibesketcher.document.formats import import_into
from vibesketcher.document.qvf import _modules, _native_structure, _stated, from_qvf
from vibesketcher.limits import check_archive
if len(data) > 4 * 2**20:
raise TransferRefused("Structure transfer exceeds 4 MiB.")
check_archive(data)
_, readers = _modules()
with readers.QvfReader(io.BytesIO(data)) as reader:
sections = [s for s in reader.sections if s["kind"] == "structure"]
if len(sections) != 1 or any(s["kind"] == "x_vibesketch.document" for s in reader.sections):
raise TransferRefused("Transfer requires one geometry-only QVF structure.")
section = sections[0]
payload = _native_structure(reader, section)
atoms = payload["atoms"]
if any(payload.get("pbc") or []) or not 1 <= len(atoms) <= 500:
raise TransferRefused("Transfer supports a nonperiodic molecule with 1–500 atoms.")
stated = _stated(section, reader.manifest.get("provenance") or {}, True)
bonds = payload.get("source_bonds")
if bonds is not None:
found = perceive(
[a["symbol"] for a in atoms],
[a["position"] for a in atoms],
charge=stated.get("charge") or 0,
)
if found is None:
raise TransferRefused("The viewer geometry cannot be drawn without guessing bonds.")
actual = {
(*sorted((b.GetBeginAtomIdx(), b.GetEndAtomIdx())), float(b.GetBondTypeAsDouble()))
for b in found.mol.GetBonds()
}
expected = {(*sorted((b["i"], b["j"])), float(b["order"])) for b in bonds["pairs"]}
if actual != expected:
raise TransferRefused(
"The 2D import would change the viewer's explicit bonds; "
"use a reviewed file import."
)
preview = from_qvf(data)
if preview.warnings or len(preview.document.species) != 1:
raise TransferRefused(
"The geometry needs a reviewed file import: "
+ "; ".join(preview.warnings or ["not one connected molecule"])
)
imported = import_into(document, data, "qvf", mode="append")
source = preview.document.species[0]
if not source.conformers:
raise TransferRefused("The imported molecule has no verified 3D coordinates.")
updated = []
matched = 0
for entry in imported.document.species:
if entry.smiles == source.smiles and entry.charge == source.charge:
matched += 1
if entry.conformers and entry.multiplicity != source.multiplicity:
raise TransferRefused(
"The existing species has a different spin; import into a new document."
)
conformers = list(entry.conformers)
for conformer in source.conformers:
if conformer not in conformers:
conformers.append(conformer)
entry = entry.model_copy(
update={"conformers": conformers, "multiplicity": source.multiplicity}
)
updated.append(entry)
if matched != 1:
raise TransferRefused("The imported molecule has no unambiguous drawing identity.")
result = imported.document.model_copy(update={"species": updated})
return Document.model_validate(result.to_json_data()), imported.warnings