Skip to content

API reference

The reference below is generated directly from the current Python sources. Names beginning with an underscore are implementation details.

Runtime

AMDockVSRuntime

AMDockVSRuntime()

Bases: AppRuntime

Public AMDockVS runtime on top of the stable MolSuite API.

Methods:

Name Description
has_shards

Does the screening library live in shards? Read off the data, never declared:

general_ligand_count

How many screening ligands are rows here — what the importer asks before offering

check_storage

(level, title, text) of a fast check of the project's payload volumes.

compact_storage_if_due

Once no job is active, release the structures no row uses and compact the payload volumes

repair_storage

Clear the payload volumes' leftovers (see check_storage); refused while a job is active.

clear_transport

Delete the files campaigns of rows packed for a queue (see clear_transport); the bytes

track_job_items

Say what a job's chunks hold, for the monitor: count() -> (done, total) in unit.

track_chunk_items

track_job_items for a job whose chunks hold per_chunk items each, the last one

job_title

The monitor's title: "Docking · gnina (CNN)" for amdock_docking_job. A job of an

measure_job

The monitor's measure: called on its polling thread, so count only reads.

set_forced_dependencies

Workflow channel: ids the NEXT submit_job call(s) must also depend on. Lets the

submit_job

Submit a job, auto-waiting for active prerequisite jobs by default.

is_queue

Whether executor_name is a cluster's queue: what goes there is a campaign.

submit_campaign

Submit an ms_flow.campaign to the queue executor_name; its key in the journal is

job_destinations

run_destinations for a job on record: where it may be continued now. Nowhere for one

resume_job

Continue a job that was canceled or interrupted, on executor_name or where it was.

resolve_job_dependencies

Union of explicit depends_on and the ids of active jobs this one should wait for.

wait_for_job

Block until the job has ended. poll_s is not used: the engine tells.

watch_job

Display tqdm progress in a terminal or notebook and return the job status.

watch_jobs

Display concurrent tqdm progress for several jobs of this session.

run_destinations

Where a job may be sent now, as (executor_name, label): the executors that are

Attributes:

Name Type Description
tools ToolAPI

Optional external programs managed by AMDockVS.

shards ShardAPI

Access registered shard containers without wrapping their records.

ligands_store

The row tools' view of the library. The shard tools build their own store.

workflow

The single active workflow (a WorkflowRunner). Panels add steps to this shared

Source code in src/amdockvs/runtime.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def __init__(self):
    super().__init__(
        app_id=AMDOCKVS_APP_ID,
        logger_name=AMDOCKVS_APP_ID,
        project_resources=AMDOCKVS_PROJECT_RESOURCES,
        # the engine in this process unless MSFLOW_ENGINE_HOST=process puts it in ms_flow's
        # child, where it does not share the GUI thread's GIL (tests: `inline_engine`)
    )
    # A host kept with no environment named is given the one of this app.
    self.workspace.host_env = self._host_env
    # What the jobs read of the project, said in the process that runs them.
    self.workspace.jobs_setup = jobs_setup
    # What the jobs sent to each cluster's queue ask of it instead of what its executor asks
    # (CPUs, time...), for this session: set by the "Queue resources" of any tool.
    self.queue_asks: dict[str, dict] = {}
    amdock_configuration = create_amdock_configuration()
    self._migrate_legacy_app_settings(amdock_configuration)
    self._configuration_sources = [
        self.workspace.settings_manager,
        amdock_configuration,
        create_contact_map_configuration(),
    ]
    self._loader_api: LoaderAPI | None = None
    # job_id -> (count() -> (done, total), unit): what the monitor shows besides chunks.
    self._job_items: dict[str, tuple] = {}
    # job_id -> what the monitor and the notices call it, titled when it is submitted.
    self._job_titles: dict[str, str] = {}
    self._molecule_api: MoleculeAPI | None = None
    self._complex_api: ComplexAPI | None = None
    self._chemistry_api: ChemistryAPI | None = None
    self._qsar_api: QSARAPI | None = None
    self._docking_api: DockingAPI | None = None
    self._binding_sites_api: BindingSiteAPI | None = None
    self._tools_api: ToolAPI | None = None
    self._shards_api: ShardAPI | None = None
    self._ligand_store = None

tools property

tools: ToolAPI

Optional external programs managed by AMDockVS.

shards property

shards: ShardAPI

Access registered shard containers without wrapping their records.

ligands_store property

ligands_store

The row tools' view of the library. The shard tools build their own store.

workflow property

workflow

The single active workflow (a WorkflowRunner). Panels add steps to this shared instance via runtime.workflow.add_step(...); it persists for the session.

has_shards

has_shards() -> bool

Does the screening library live in shards? Read off the data, never declared: a project holds a sharded library by holding shards.

Source code in src/amdockvs/runtime.py
312
313
314
315
316
def has_shards(self) -> bool:
    """Does the screening library live in shards? Read off the data, never declared:
    a project holds a sharded library by holding shards."""
    self._require_active_project()
    return has_shards(self.workspace.project_db)

general_ligand_count

general_ligand_count() -> int

How many screening ligands are rows here — what the importer asks before offering to shard, since the two libraries cannot coexist.

Source code in src/amdockvs/runtime.py
318
319
320
321
322
def general_ligand_count(self) -> int:
    """How many screening ligands are rows here — what the importer asks before offering
    to shard, since the two libraries cannot coexist."""
    self._require_active_project()
    return general_ligand_count(self.workspace.project_db)

check_storage

check_storage() -> tuple[str, str, str]

(level, title, text) of a fast check of the project's payload volumes.

Source code in src/amdockvs/runtime.py
436
437
438
439
440
441
def check_storage(self) -> tuple[str, str, str]:
    """(level, title, text) of a fast check of the project's payload volumes."""
    from amdockvs.project.storage import check_storage

    self._require_active_project()
    return check_storage(self.workspace.project_db)

compact_storage_if_due

compact_storage_if_due() -> dict | None

Once no job is active, release the structures no row uses and compact the payload volumes that are mostly dead bytes; the stats, or None when nothing was due.

Source code in src/amdockvs/runtime.py
443
444
445
446
447
448
449
450
451
def compact_storage_if_due(self) -> dict | None:
    """Once no job is active, release the structures no row uses and compact the payload volumes
    that are mostly dead bytes; the stats, or None when nothing was due."""
    from amdockvs.project.storage import compact_if_idle

    self._require_active_project()
    return compact_if_idle(
        self.workspace.project_db, busy=bool(self.list_jobs(statuses=NON_TERMINAL_JOB_STATUSES))
    )

repair_storage

repair_storage()

Clear the payload volumes' leftovers (see check_storage); refused while a job is active.

Source code in src/amdockvs/runtime.py
453
454
455
456
457
458
459
460
def repair_storage(self):
    """Clear the payload volumes' leftovers (see `check_storage`); refused while a job is active."""
    from amdockvs.project.storage import repair_if_idle

    self._require_active_project()
    return repair_if_idle(
        self.workspace.project_db, busy=bool(self.list_jobs(statuses=NON_TERMINAL_JOB_STATUSES))
    )

clear_transport

clear_transport() -> int

Delete the files campaigns of rows packed for a queue (see clear_transport); the bytes freed. Refused while a job is active or interrupted: a campaign going on there needs them.

Source code in src/amdockvs/runtime.py
462
463
464
465
466
467
468
469
470
def clear_transport(self) -> int:
    """Delete the files campaigns of rows packed for a queue (see `clear_transport`); the bytes
    freed. Refused while a job is active or interrupted: a campaign going on there needs them."""
    from amdockvs.docking.campaign import clear_transport

    self._require_active_project()
    if any(not str(job.status).startswith(("completed", "failed", "canceled")) for job in self.workspace.jobs()):
        raise RuntimeError("Jobs are running; clear the queue files once they end.")
    return clear_transport(self.workspace.project_db)

track_job_items

track_job_items(job_id: str, count, *, unit: str) -> None

Say what a job's chunks hold, for the monitor: count() -> (done, total) in unit.

Kept for this session only; a job of an earlier one shows its chunks alone.

Source code in src/amdockvs/runtime.py
492
493
494
495
496
497
def track_job_items(self, job_id: str, count, *, unit: str) -> None:
    """Say what a job's chunks hold, for the monitor: `count() -> (done, total)` in `unit`.

    Kept for this session only; a job of an earlier one shows its chunks alone.
    """
    self._job_items[str(job_id)] = (count, str(unit))

track_chunk_items

track_chunk_items(job_id: str, total: int, per_chunk: int, *, unit: str) -> None

track_job_items for a job whose chunks hold per_chunk items each, the last one fewer: read from the engine's own count, so the monitor's poll touches no database.

Source code in src/amdockvs/runtime.py
499
500
501
502
503
504
505
506
507
508
def track_chunk_items(self, job_id: str, total: int, per_chunk: int, *, unit: str) -> None:
    """`track_job_items` for a job whose chunks hold `per_chunk` items each, the last one
    fewer: read from the engine's own count, so the monitor's poll touches no database."""
    engine = self.workspace.engine

    def count():
        done = engine.status(self._engine_ids()[str(job_id)]).chunks_done
        return min(done * per_chunk, total), total

    self.track_job_items(job_id, count, unit=unit)

job_title

job_title(job_id: str, name: str) -> str

The monitor's title: "Docking · gnina (CNN)" for amdock_docking_job. A job of an earlier session is titled from the params the journal kept of it.

Source code in src/amdockvs/runtime.py
510
511
512
513
514
515
516
517
518
519
520
def job_title(self, job_id: str, name: str) -> str:
    """The monitor's `title`: "Docking · gnina (CNN)" for `amdock_docking_job`. A job of an
    earlier session is titled from the params the journal kept of it."""
    title = self._job_titles.get(str(job_id))
    if title is None:
        try:
            params = self.workspace.origin(str(job_id)).get("params")
        except Exception:  # noqa: BLE001 - not on record: its kind alone
            params = None
        title = self._job_titles[str(job_id)] = job_title(name, params)
    return title

measure_job

measure_job(job_id: str) -> dict | None

The monitor's measure: called on its polling thread, so count only reads.

Source code in src/amdockvs/runtime.py
522
523
524
525
526
527
528
529
def measure_job(self, job_id: str) -> dict | None:
    """The monitor's `measure`: called on its polling thread, so `count` only reads."""
    tracked = self._job_items.get(str(job_id))
    if tracked is None:
        return None
    count, unit = tracked
    done, total = count()
    return {"done": int(done), "total": int(total or 0), "unit": unit}

set_forced_dependencies

set_forced_dependencies(job_ids: Optional[list[str]]) -> None

Workflow channel: ids the NEXT submit_job call(s) must also depend on. Lets the orchestrator inject same-category serialization that the category auto-deps don't cover, without every submit API needing a depends_on parameter. Cleared by passing None.

Source code in src/amdockvs/runtime.py
541
542
543
544
545
def set_forced_dependencies(self, job_ids: Optional[list[str]]) -> None:
    """Workflow channel: ids the NEXT submit_job call(s) must also depend on. Lets the
    orchestrator inject same-category serialization that the category auto-deps don't cover,
    without every submit API needing a depends_on parameter. Cleared by passing None."""
    self._forced_dependencies = list(job_ids) if job_ids else None

submit_job

submit_job(job, *, params: Any = None, executor_name: Optional[str] = None, cpu_required: Optional[int] = None, max_job_cpu: Optional[int] = None, max_inflight_tasks: Optional[int] = None, total_chunks: Optional[int] = None, depends_on: Optional[list[str]] = None, priority: int = 0, auto_depends: bool = True, queue_behind: Optional[str] = None, autobatch: int = 0) -> str

Submit a job, auto-waiting for active prerequisite jobs by default.

autobatch (a number of chunks) lets the executor size its tasks: they start at that many of the job's chunks, never fewer than one, and grow while bigger ones pay (see ms_flow.Engine.submit). Its chunks then run through the job's run_chunks; an executor that takes one chunk to a task runs them one by one.

queue_behind names a lane (e.g. "docking"): the job goes a priority level below every active job of that lane on the same executor, so long jobs of a kind run one after the other, each on what the ones before it leave free, instead of sharing the machine.

With auto_depends=True (default) the job is held until every active job of its prerequisite categories finishes, so a deferred pipeline can be queued at once. Pass auto_depends=False to submit immediately regardless of running jobs. Returns the key of the job in the project's journal, which is its id everywhere here.

Source code in src/amdockvs/runtime.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
def submit_job(
    self,
    job,
    *,
    params: Any = None,
    executor_name: Optional[str] = None,
    cpu_required: Optional[int] = None,
    max_job_cpu: Optional[int] = None,
    max_inflight_tasks: Optional[int] = None,
    total_chunks: Optional[int] = None,
    depends_on: Optional[list[str]] = None,
    priority: int = 0,
    auto_depends: bool = True,
    queue_behind: Optional[str] = None,
    autobatch: int = 0,
) -> str:
    """Submit a job, auto-waiting for active prerequisite jobs by default.

    `autobatch` (a number of chunks) lets the executor size its tasks: they start at that
    many of the job's chunks, never fewer than one, and grow while bigger ones pay (see
    `ms_flow.Engine.submit`). Its chunks then run through the job's `run_chunks`; an
    executor that takes one chunk to a task runs them one by one.

    `queue_behind` names a lane (e.g. "docking"): the job goes a priority level below every
    active job of that lane on the same executor, so long jobs of a kind run one after the
    other, each on what the ones before it leave free, instead of sharing the machine.

    With auto_depends=True (default) the job is held until every active job of its
    prerequisite categories finishes, so a deferred pipeline can be queued at once.
    Pass auto_depends=False to submit immediately regardless of running jobs.
    Returns the key of the job in the project's journal, which is its id everywhere here.
    """
    self._require_active_project()
    depends_on = list(depends_on or [])
    depends_on += [job_id for job_id in getattr(self, "_forced_dependencies", None) or () if job_id not in depends_on]
    if auto_depends:
        depends_on = self.resolve_job_dependencies(job, depends_on) or []
    workspace = self.workspace
    job_config = self._job_config()
    job_params = job.validate_params(params)
    total = total_chunks if total_chunks is not None else job.count_chunks(job_params, config=job_config)
    job_id = uuid4().hex
    engine_ids = self._engine_ids()
    executor = self._run_on(job, executor_name)
    if queue_behind:
        priority += self._behind(queue_behind, executor)
    engine_ids[job_id] = workspace.submit(
        job.engine,
        job_params,
        key=job_id,
        executor=executor,
        **self._asks(executor),
        # A job that ended in an earlier session has nothing left to wait for.
        after=[engine_ids[dep] for dep in depends_on if dep in engine_ids],
        total=total,
        cpu=cpu_required,
        window=max_inflight_tasks,
        max_cpu=max_job_cpu,
        priority=priority,
        **({"thread": True} if job.on_thread is not None and job.on_thread(job_params) else {}),
        # ponytail: "thread" is the one executor of a chunk to a task; by name, as the engine may be a proxy.
        **({"batch": 1, "batched": True, "autobatch": int(autobatch)}
           if autobatch and job.run_chunks is not None and executor != "thread" else {}),
    )
    if queue_behind:
        self._lanes()[job_id] = (queue_behind, executor, priority)
    self._job_titles[job_id] = job_title(str(getattr(job, "name", "") or ""), job_params)
    # Single funnel for "a job just started" UI feedback (the main window plugs a toast in
    # here). May fire from a worker thread, so the hook must be thread-safe (a Qt signal).
    hook = getattr(self, "on_job_submitted", None)
    if hook is not None:
        try:
            hook(self._job_titles[job_id], job_id)
        except Exception:  # noqa: BLE001 - feedback must never break a submit
            pass
    return job_id

is_queue

is_queue(executor_name: Optional[str]) -> bool

Whether executor_name is a cluster's queue: what goes there is a campaign.

Source code in src/amdockvs/runtime.py
624
625
626
627
def is_queue(self, executor_name: Optional[str]) -> bool:
    """Whether `executor_name` is a cluster's queue: what goes there is a campaign."""
    executor = self.workspace.settings_manager.settings.executors.get(str(executor_name or ""))
    return executor is not None and executor.kind == "queue"

submit_campaign

submit_campaign(job, *, params: Any, executor_name: str, priority: int = 0) -> str

Submit an ms_flow.campaign to the queue executor_name; its key in the journal is its identity, so the same campaign submitted again is the job that already follows it.

ponytail: its elements are made now, from what the project has now: it waits for no job.

Source code in src/amdockvs/runtime.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
def submit_campaign(self, job, *, params: Any, executor_name: str, priority: int = 0) -> str:
    """Submit an `ms_flow.campaign` to the queue `executor_name`; its key in the journal is
    its identity, so the same campaign submitted again is the job that already follows it.

    ponytail: its elements are made now, from what the project has now: it waits for no job.
    """
    self._require_active_project()
    self._job_config()  # what its source and writer read of the project
    engine_id = self.workspace.submit(job, params, executor=executor_name, priority=priority,
                                      **self._asks(executor_name))
    job_id = str(self.workspace.engine.status(engine_id).key)
    self._engine_ids()[job_id] = engine_id
    self._job_titles[job_id] = job_title(str(job.__job__["name"]), params)
    hook = getattr(self, "on_job_submitted", None)
    if hook is not None:
        try:
            hook(self._job_titles[job_id], job_id)
        except Exception:  # noqa: BLE001 - feedback must never break a submit
            pass
    return job_id

job_destinations

job_destinations(job_id: str) -> list[tuple[str, str]]

run_destinations for a job on record: where it may be continued now. Nowhere for one that cannot be submitted again; a campaign, only to an active queue.

Source code in src/amdockvs/runtime.py
665
666
667
668
669
670
671
672
673
674
def job_destinations(self, job_id: str) -> list[tuple[str, str]]:
    """`run_destinations` for a job on record: where it may be continued now. Nowhere for one
    that cannot be submitted again; a campaign, only to an active queue."""
    try:
        job, was_on = self._recorded_job(job_id)
        if job is None:
            return [(name, label) for name, label in self.run_destinations() if self.is_queue(name)]
        return self.run_destinations(job)
    except Exception:  # noqa: BLE001 - not on record, or its declaration is gone
        return []

resume_job

resume_job(job_id: str, executor_name: Optional[str] = None) -> str

Continue a job that was canceled or interrupted, on executor_name or where it was.

A job that is still running is canceled first and waited for, which is how it is moved to another executor: not from a thread that cannot wait. It waits for the jobs its kind waits for, as when it was submitted.

Source code in src/amdockvs/runtime.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
def resume_job(self, job_id: str, executor_name: Optional[str] = None) -> str:
    """Continue a job that was canceled or interrupted, on `executor_name` or where it was.

    A job that is still running is canceled first and waited for, which is how it is moved
    to another executor: not from a thread that cannot wait. It waits for the jobs its kind
    waits for, as when it was submitted.
    """
    self._require_active_project()
    job_id = str(job_id)
    job, was_on = self._recorded_job(job_id)
    if job is None:  # a campaign: back to its queue, where what it has there is found again by its key
        executor = executor_name or was_on
        if not self.is_queue(executor):
            raise ValueError(f"a campaign goes to a cluster's queue, and `{executor}` is not one")
        self._job_config()  # what its writer and its end read of the project
        self._engine_ids()[job_id] = self.workspace.move(job_id, executor, **self._asks(executor))
        return job_id
    executor = self._run_on(job, executor_name or was_on)
    if job.name == "amdock_docking_job" and self.is_queue(executor):
        return self.docking.move_to_queue(job_id, executor)  # one job of the queue, not a task per chunk
    self._job_config()
    engine_ids = self._engine_ids()
    waits = [engine_ids[dep] for dep in self.resolve_job_dependencies(job) or ()
             if dep in engine_ids and dep != job_id]
    engine_ids[job_id] = self.workspace.move(job_id, executor, after=waits)
    return job_id

resolve_job_dependencies

resolve_job_dependencies(job, explicit: Optional[list[str]] = None) -> Optional[list[str]]

Union of explicit depends_on and the ids of active jobs this one should wait for.

Source code in src/amdockvs/runtime.py
724
725
726
727
728
729
730
731
732
733
734
735
def resolve_job_dependencies(self, job, explicit: Optional[list[str]] = None) -> Optional[list[str]]:
    """Union of explicit depends_on and the ids of active jobs this one should wait for."""
    category = _job_category(getattr(job, "name", "") or "")
    prereqs = _JOB_PREREQS.get(category or "", ())
    deps: list[str] = list(explicit or [])
    if prereqs or category == "chemistry":
        for status in self.list_jobs(statuses=NON_TERMINAL_JOB_STATUSES):
            active_category = _job_category(status.task_type)
            serial_chemistry = category == "chemistry" and active_category == "chemistry"
            if (active_category in prereqs or serial_chemistry) and status.job_id not in deps:
                deps.append(status.job_id)
    return deps or None

wait_for_job

wait_for_job(job_id: str, *, poll_s: float = 0.2) -> JobStatus

Block until the job has ended. poll_s is not used: the engine tells.

Source code in src/amdockvs/runtime.py
750
751
752
753
754
755
756
757
758
759
def wait_for_job(self, job_id: str, *, poll_s: float = 0.2) -> JobStatus:
    """Block until the job has ended. `poll_s` is not used: the engine tells."""
    self._require_active_project()
    engine_id = self._engine_ids().get(str(job_id))
    if engine_id is None:  # of an earlier session: it ended with it
        status = self.get_job_status(job_id)
        if status is None:
            raise KeyError(f"Unknown job: {job_id}")
        return status
    return self._job_status_from_snapshot(self.workspace.engine.wait(engine_id))

watch_job

watch_job(job_id: str, *, poll_s: float = 0.2) -> JobStatus

Display tqdm progress in a terminal or notebook and return the job status.

Source code in src/amdockvs/runtime.py
761
762
763
def watch_job(self, job_id: str, *, poll_s: float = 0.2) -> JobStatus:
    """Display tqdm progress in a terminal or notebook and return the job status."""
    return self.watch_jobs([job_id], poll_s=poll_s)[str(job_id)]

watch_jobs

watch_jobs(job_ids: Iterable[str], *, poll_s: float = 0.2) -> dict[str, JobStatus]

Display concurrent tqdm progress for several jobs of this session.

Source code in src/amdockvs/runtime.py
765
766
767
768
769
770
771
772
773
def watch_jobs(self, job_ids: Iterable[str], *, poll_s: float = 0.2) -> dict[str, JobStatus]:
    """Display concurrent tqdm progress for several jobs of this session."""
    self._require_active_project()
    from ms_flow.progress import watch_jobs

    job_ids = [str(item) for item in job_ids]
    engine_ids = self._engine_ids()
    snapshots = watch_jobs(self.workspace.engine, [engine_ids[job_id] for job_id in job_ids], poll_s=poll_s)
    return {job_id: self._job_status_from_snapshot(snapshots[engine_ids[job_id]]) for job_id in job_ids}

run_destinations

run_destinations(job=None) -> list[tuple[str, str]]

Where a job may be sent now, as (executor_name, label): the executors that are active, the default one first. With job, only the ones that job can run on.

Source code in src/amdockvs/runtime.py
808
809
810
811
812
813
814
815
816
817
818
def run_destinations(self, job=None) -> list[tuple[str, str]]:
    """Where a job may be sent now, as (executor_name, label): the executors that are
    active, the default one first. With `job`, only the ones that job can run on.
    """
    self._require_active_project()
    rows = [row for row in self.workspace.executors() if row["state"] == "on"]
    # ponytail: `hpc` in the old list of a job is what says its worker needs nothing of
    # this machine but its payload and the files marked in it; one flag when the lists go.
    if job is not None and "hpc" not in job.supported_executors:
        rows = [row for row in rows if row["hosts"] == ["local"]]
    return [(row["name"], row["name"]) for row in sorted(rows, key=lambda row: not row["default"])]

Molecules

api

Classes:

Name Description
MoleculeAPI

MoleculeAPI dataclass

MoleculeAPI(runtime: Any)

Methods:

Name Description
get

Return one molecule without exposing the project session to callers.

excluded_ids

Every excluded molecule (idx_mol_excluded holds only those): a run's "before".

excluded_since

(id, name, reason) of the molecules excluded now but not in before — what a run

details

Load the complete Details-panel projection for a molecule.

list_sets

List saved molecule sets newest first.

resolve_set

Resolve UI/catalog set values into the public typed set reference.

sync_set_membership

Reconcile the denormalized in_set molecule flag.

scope_clause

Opaque SmartTable adapter for a public molecule scope.

evaluate_filter

Count filter outcomes without mutating molecules.

apply_filter

Apply an evaluated filter or persist its matches as a molecule set.

molblock

The molecule's current structure as a molfile — what the 2D editor opens.

dependents

What hangs from this molecule's structure and would go if an edit replaced it.

edit

Give a molecule an edited structure (a molfile from the 2D editor).

stream

Compatibility entry point; prefer iterating the returned Selection.

library_shape

(the library is sharded, any ligand row exists) — two one-row lookups.

has_receptors

Whether any receptor row exists — a one-row lookup.

shard_counts

Inventory of the sharded library: shards, molecules in them, and how many are prepared.

library_stats

What the Project dialog shows of a sharded library: see molecules.library_stats.

shard_preps

One shard's preparations: family -> (prepared records, failed records).

select_fragment

Make another component of the imported original the molecule's current structure.

get

get(molecule_id: int) -> MoleculeRecord | None

Return one molecule without exposing the project session to callers.

Source code in src/amdockvs/molecules/api.py
121
122
123
124
125
def get(self, molecule_id: int) -> MoleculeRecord | None:
    """Return one molecule without exposing the project session to callers."""
    self.runtime._require_active_project()
    with self.runtime.workspace.project_db.get_session() as session:
        return session.get(MoleculeRecord, int(molecule_id))

excluded_ids

excluded_ids() -> set[int]

Every excluded molecule (idx_mol_excluded holds only those): a run's "before".

Source code in src/amdockvs/molecules/api.py
127
128
129
130
131
def excluded_ids(self) -> set[int]:
    """Every excluded molecule (`idx_mol_excluded` holds only those): a run's "before"."""
    self.runtime._require_active_project()
    with self.runtime.workspace.project_db.get_session() as session:
        return set(session.exec(select(MoleculeRecord.id).where(MoleculeRecord.excluded == True)).all())  # noqa: E712

excluded_since

excluded_since(before: set[int], *, limit: int = 10000) -> list[tuple[int, str, str]]

(id, name, reason) of the molecules excluded now but not in before — what a run failed. ponytail: a run alongside it mixes its failures in; per-job ids if that matters.

Source code in src/amdockvs/molecules/api.py
133
134
135
136
137
138
139
140
141
142
143
144
145
def excluded_since(self, before: set[int], *, limit: int = 10_000) -> list[tuple[int, str, str]]:
    """``(id, name, reason)`` of the molecules excluded now but not in ``before`` — what a run
    failed. ponytail: a run alongside it mixes its failures in; per-job ids if that matters."""
    new = sorted(self.excluded_ids() - set(before))[: int(limit)]
    if not new:
        return []
    with self.runtime.workspace.project_db.get_session() as session:
        rows = session.exec(
            select(MoleculeRecord.id, MoleculeRecord.name, MoleculeRecord.exclusion_reason)
            .where(MoleculeRecord.id.in_(new))
            .order_by(MoleculeRecord.id)
        ).all()
    return [(int(i), str(name or ""), str(reason or "")) for i, name, reason in rows]

details

details(molecule_id: int) -> Details | None

Load the complete Details-panel projection for a molecule.

Source code in src/amdockvs/molecules/api.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def details(self, molecule_id: int) -> Details | None:
    """Load the complete Details-panel projection for a molecule."""
    self.runtime._require_active_project()
    resolved_id = int(molecule_id)
    with self.runtime.workspace.project_db.get_session() as session:
        molecule = session.get(MoleculeRecord, resolved_id)
        if molecule is None:
            return None
        binding_sites = tuple(session.exec(
            select(BindingSite)
            .where(BindingSite.molecule_id == resolved_id)
            .order_by(BindingSite.id)
        ).all())
        receptor_complexes = tuple(session.exec(
            select(ComplexRecord)
            .where(ComplexRecord.receptor_molecule_id == resolved_id)
            .order_by(ComplexRecord.id.desc())
        ).all())
        ligand_complexes = tuple(session.exec(
            select(ComplexRecord)
            .where(ComplexRecord.ligand_molecule_id == resolved_id)
            .order_by(ComplexRecord.id.desc())
        ).all())
        activities = tuple(session.exec(
            select(LigandActivity)
            .where(LigandActivity.molecule_id == resolved_id)
            .order_by(LigandActivity.id.desc())
        ).all())
        structure = molecule_payload_id(molecule)
        current_model = None if structure is None else session.exec(
            select(MoleculeModel)
            .where(MoleculeModel.molecule_id == resolved_id)
            .where(MoleculeModel.payload_id == int(structure))
            .order_by(MoleculeModel.id.desc())
        ).first()
        plddt_model = current_model
        if current_model is None or current_model.source != ModelSource.ESMFOLD:
            plddt_model = session.exec(
                select(MoleculeModel)
                .where(MoleculeModel.molecule_id == resolved_id)
                .where(MoleculeModel.source == ModelSource.ESMFOLD)
                .where(MoleculeModel.payload_id.is_not(None))
                .order_by(MoleculeModel.id.desc())
            ).first()

    def model_data(model):
        if model is None or model.data_payload_id is None:
            return None
        import json

        from amdockvs.core.payloads import read_structure

        data = json.loads(read_structure(self.runtime.workspace.project_db, model.data_payload_id)[0])
        data.pop("pae", None)
        return data

    current_data = model_data(current_model)
    return self.Details(
        molecule=molecule,
        binding_sites=binding_sites,
        receptor_complexes=receptor_complexes,
        ligand_complexes=ligand_complexes,
        activities=activities,
        current_model=current_model,
        current_model_data=current_data,
        plddt_model=plddt_model,
        plddt_model_data=current_data if plddt_model is current_model else model_data(plddt_model),
    )

list_sets

list_sets() -> list[SetRecord]

List saved molecule sets newest first.

Source code in src/amdockvs/molecules/api.py
216
217
218
219
220
def list_sets(self) -> list[SetRecord]:
    """List saved molecule sets newest first."""
    self.runtime._require_active_project()
    with self.runtime.workspace.project_db.get_session() as session:
        return list(session.exec(select(SetRecord).order_by(SetRecord.id.desc())).all())

resolve_set

resolve_set(source: MoleculeSetRef | SetRecord | int) -> MoleculeSetRef

Resolve UI/catalog set values into the public typed set reference.

Source code in src/amdockvs/molecules/api.py
222
223
224
225
226
227
228
229
230
231
def resolve_set(self, source: MoleculeSetRef | SetRecord | int) -> MoleculeSetRef:
    """Resolve UI/catalog set values into the public typed set reference."""
    self.runtime._require_active_project()
    if isinstance(source, MoleculeSetRef):
        return source
    set_id = int(source.id if isinstance(source, SetRecord) else source)
    record = get_molecule_set(self.runtime.workspace.project_db, set_id)
    if record is None:
        raise ValueError(f"Molecule set {set_id} does not exist.")
    return MoleculeSetRef(id=set_id, kind="snapshot")

sync_set_membership

sync_set_membership() -> None

Reconcile the denormalized in_set molecule flag.

Source code in src/amdockvs/molecules/api.py
233
234
235
236
def sync_set_membership(self) -> None:
    """Reconcile the denormalized ``in_set`` molecule flag."""
    self.runtime._require_active_project()
    sync_all_molecule_in_set_flags(self.runtime.workspace.project_db)

scope_clause

scope_clause(scope: MoleculeScope | Selection[Any])

Opaque SmartTable adapter for a public molecule scope.

ORM expressions stay behind the AMDock API; UI callers only pass the returned value to SmartTableView's external-clause hook.

Source code in src/amdockvs/molecules/api.py
238
239
240
241
242
243
244
245
246
247
248
def scope_clause(self, scope: MoleculeScope | Selection[Any]):
    """Opaque SmartTable adapter for a public molecule scope.

    ORM expressions stay behind the AMDock API; UI callers only pass the returned value to
    SmartTableView's external-clause hook.
    """
    self.runtime._require_active_project()
    from amdockvs.molecules import filtering as filter_sql

    conditions = filter_sql.scope_conditions(self.runtime.workspace.project_db, as_molecule_scope(scope))
    return and_(*conditions) if conditions else None

evaluate_filter

evaluate_filter(scope: MoleculeScope | Selection[Any], criteria, *, exclusion_reason_prefix: str = '') -> dict[str, int]

Count filter outcomes without mutating molecules.

Source code in src/amdockvs/molecules/api.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def evaluate_filter(
    self,
    scope: MoleculeScope | Selection[Any],
    criteria,
    *,
    exclusion_reason_prefix: str = "",
) -> dict[str, int]:
    """Count filter outcomes without mutating molecules."""
    self.runtime._require_active_project()
    from amdockvs.molecules import filtering as filter_sql

    conditions = filter_sql.scope_conditions(self.runtime.workspace.project_db, as_molecule_scope(scope))
    prefix = str(exclusion_reason_prefix or "").strip()
    if prefix:
        conditions.append(MoleculeRecord.exclusion_reason.like(f"{prefix}%"))
    return filter_sql.counts(self.runtime.workspace.project_db, conditions, criteria)

apply_filter

apply_filter(scope: MoleculeScope | Selection[Any], criteria, *, action: str, reason: str = '', exclusion_reason_prefix: str = '', set_name: str = '') -> tuple[int, int | None]

Apply an evaluated filter or persist its matches as a molecule set.

Source code in src/amdockvs/molecules/api.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def apply_filter(
    self,
    scope: MoleculeScope | Selection[Any],
    criteria,
    *,
    action: str,
    reason: str = "",
    exclusion_reason_prefix: str = "",
    set_name: str = "",
) -> tuple[int, int | None]:
    """Apply an evaluated filter or persist its matches as a molecule set."""
    self.runtime._require_active_project()
    from amdockvs.molecules import filtering as filter_sql

    normalized_action = str(action or "").strip().lower()
    if normalized_action not in {"enrich", "recover", "tag"}:
        raise ValueError(f"Unsupported molecule-filter action: {action!r}")
    conditions = filter_sql.scope_conditions(self.runtime.workspace.project_db, as_molecule_scope(scope))
    prefix = str(exclusion_reason_prefix or "").strip()
    if prefix:
        conditions.append(MoleculeRecord.exclusion_reason.like(f"{prefix}%"))
    if normalized_action == "tag":
        ids = filter_sql.matched_ids(self.runtime.workspace.project_db, conditions, criteria)
        ref = self.create_set(
            ids,
            name=set_name,
            kind="filter",
            metadata={"source": str(reason or "")},
        )
        return len(ids), int(ref.id)
    return filter_sql.apply_state(
        self.runtime.workspace.project_db,
        conditions,
        criteria,
        activate_matches=normalized_action == "recover",
        exclude_nonmatches=normalized_action == "enrich",
        reason=str(reason or ""),
    )

molblock

molblock(molecule_id: int) -> str

The molecule's current structure as a molfile — what the 2D editor opens.

Source code in src/amdockvs/molecules/api.py
312
313
314
315
316
317
318
319
320
321
322
def molblock(self, molecule_id: int) -> str:
    """The molecule's current structure as a molfile — what the 2D editor opens."""
    from rdkit import Chem

    from amdockvs.chemistry.structures import molecule_mol

    molecule = self.get(molecule_id)
    mol = molecule_mol(self.runtime.workspace.project_db, molecule) if molecule is not None else None
    if mol is None:
        raise ValueError(f"Molecule {molecule_id} has no structure.")
    return Chem.MolToMolBlock(mol)

dependents

dependents(molecule_id: int) -> dict[str, int]

What hangs from this molecule's structure and would go if an edit replaced it.

Source code in src/amdockvs/molecules/api.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def dependents(self, molecule_id: int) -> dict[str, int]:
    """What hangs from this molecule's structure and would go if an edit replaced it."""
    from sqlalchemy import func, or_

    from amdockvs.models import DockingResultRecord
    from amdockvs.models.qsar import LigandActivity, QSARPrediction

    counts = {}
    with self.runtime.workspace.project_db.get_session() as session:
        for label, model, clause in (
            ("activities", LigandActivity, LigandActivity.molecule_id == molecule_id),
            ("docking results", DockingResultRecord, or_(DockingResultRecord.ligand_molecule_id == molecule_id,
                                                         DockingResultRecord.receptor_molecule_id == molecule_id)),
            ("QSAR predictions", QSARPrediction, QSARPrediction.molecule_id == molecule_id),
        ):
            counts[label] = int(session.exec(select(func.count()).select_from(model).where(clause)).one())
    return {label: n for label, n in counts.items() if n}

edit

edit(molecule_id: int, molblock: str, *, copy: bool = False) -> int | None

Give a molecule an edited structure (a molfile from the 2D editor).

copy=False replaces it: everything computed from the old structure goes (clear_derived: conformers, engine preparations, descriptors, fingerprints, docking results...) and so do its activities, measured on the old compound; the imported original (stored_payload_id), sets and complexes stay. copy=True leaves the molecule alone and adds the edit as a new one, with nothing of the old one's but its role. Returns the id holding the edit, or None when the drawing is still the same compound, which changes nothing.

Source code in src/amdockvs/molecules/api.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def edit(self, molecule_id: int, molblock: str, *, copy: bool = False) -> int | None:
    """Give a molecule an edited structure (a molfile from the 2D editor).

    `copy=False` replaces it: everything computed from the old structure goes (`clear_derived`:
    conformers, engine preparations, descriptors, fingerprints, docking results...) and so do its
    activities, measured on the old compound; the imported original (stored_payload_id), sets and
    complexes stay. `copy=True` leaves the molecule alone and adds the edit as a new one, with
    nothing of the old one's but its role. Returns the id holding the edit, or None when the
    drawing is still the same compound, which changes nothing."""
    self.runtime._require_active_project()
    from sqlalchemy import delete as sql_delete

    from amdockvs.chemistry.structures import molecule_mol, sdf_payload
    from amdockvs.core.payloads import payload_store
    from amdockvs.io.rows import identity_representations, structure_fields
    from amdockvs.models.qsar import LigandActivity
    from amdockvs.molecules.editing import edited_structure
    from amdockvs.project.deletion import clear_derived

    project_db = self.runtime.workspace.project_db
    molecule = self.get(molecule_id)
    if molecule is None:
        raise ValueError(f"Molecule {molecule_id} does not exist.")
    mol = edited_structure(molblock, molecule_mol(project_db, molecule))
    if mol is None:
        return None
    fields = structure_fields(mol)
    identity = {key: fields.pop(key) for key in ("inchikey", "canonical_smiles")}
    store = payload_store(project_db)
    if not copy:
        clear_derived(project_db, [molecule.id])
    with project_db.get_session() as session:
        edited_payload, = store.put(session, [sdf_payload(mol)])
        if copy:
            parent = session.get(MoleculeRecord, int(molecule.id))
            row = MoleculeRecord(**parent.model_dump(exclude={"id", "ro5_violations"}))
            row.name = f"{parent.name} (edited)"
            row.stored_payload_id = edited_payload  # the edit is all this molecule ever had
            row.in_set = False
            metadata = {"edited_from": int(parent.id)}
            replaced = None
        else:
            session.exec(sql_delete(LigandActivity).where(LigandActivity.molecule_id == int(molecule.id)))
            row = session.get(MoleculeRecord, int(molecule.id))
            metadata = sanitize_molecule_extra_data(row.extra_data)
            for stale in ("chemistry", "history", "state"):  # described the structure that is gone
                metadata.pop(stale, None)
            replaced = row.current_payload_id
        row.current_payload_id = edited_payload
        for key, value in fields.items():
            setattr(row, key, value)
        row.is_minimized = False
        metadata["edited"] = True
        row.extra_data = metadata
        session.add(row)
        session.flush()
        for representation in identity_representations(identity, molecule_id=int(row.id)):
            session.merge(MoleculeRepresentation(**representation))
        session.commit()
        edited_id = int(row.id)
    if replaced:
        store.release([replaced])  # an earlier edit's bytes; the import is still referenced, so it stays
    return edited_id

stream

stream(scope: MoleculeScope | Selection[MoleculeRecord] | None = None) -> Iterator[MoleculeRecord]

Compatibility entry point; prefer iterating the returned Selection.

Source code in src/amdockvs/molecules/api.py
443
444
445
446
447
def stream(self, scope: MoleculeScope | Selection[MoleculeRecord] | None = None) -> Iterator[MoleculeRecord]:
    """Compatibility entry point; prefer iterating the returned Selection."""
    resolved = as_molecule_scope(scope) if scope is not None else as_molecule_scope(self.all())
    assert resolved is not None
    yield from self._stream_scope(resolved)

library_shape

library_shape() -> tuple[bool, bool]

(the library is sharded, any ligand row exists) — two one-row lookups.

What the catalog bar needs to know and the only thing it needs the db for: Shards is there when there are shards, Ligands lights up when there is any ligand row at all.

Source code in src/amdockvs/molecules/api.py
471
472
473
474
475
476
477
478
479
480
481
def library_shape(self) -> tuple[bool, bool]:
    """`(the library is sharded, any ligand row exists)` — two one-row lookups.

    What the catalog bar needs to know and the only thing it needs the db for: Shards is
    there when there are shards, Ligands lights up when there is any ligand row at all.
    """
    from amdockvs.molecules.storage import has_ligand_rows, has_shards

    self.runtime._require_active_project()
    project_db = self.runtime.workspace.project_db
    return bool(has_shards(project_db)), has_ligand_rows(project_db)

has_receptors

has_receptors() -> bool

Whether any receptor row exists — a one-row lookup.

Source code in src/amdockvs/molecules/api.py
483
484
485
486
487
488
def has_receptors(self) -> bool:
    """Whether any receptor row exists — a one-row lookup."""
    from amdockvs.molecules.storage import has_receptor_rows

    self.runtime._require_active_project()
    return has_receptor_rows(self.runtime.workspace.project_db)

shard_counts

shard_counts(*, engine: str = 'ad4') -> dict[str, int]

Inventory of the sharded library: shards, molecules in them, and how many are prepared.

Preparation is engine-specific and does not rewrite the chemical inventory.

Source code in src/amdockvs/molecules/api.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
def shard_counts(self, *, engine: str = "ad4") -> dict[str, int]:
    """Inventory of the sharded library: shards, molecules in them, and how many are prepared.

    Preparation is engine-specific and does not rewrite the chemical inventory.
    """
    from amdockvs.molecules.storage import ShardStore, iter_prepared_shards, shard_scope_spec

    self.runtime._require_active_project()
    store = ShardStore(self.runtime.workspace.project_db)
    whole = shard_scope_spec()
    prepared = list(iter_prepared_shards(self.runtime.workspace.project_db, engine=engine))
    return {
        "shards": store.count(whole),
        "records": store.record_count(whole),
        "prepared": len(prepared),
        "prepared_records": sum(int(row.get("n_records") or 0) for row in prepared),
    }

library_stats

library_stats()

What the Project dialog shows of a sharded library: see molecules.library_stats.

Source code in src/amdockvs/molecules/api.py
508
509
510
511
512
513
514
515
516
517
518
def library_stats(self):
    """What the Project dialog shows of a sharded library: see `molecules.library_stats`."""
    from amdockvs.core.constants import RESOURCE_SHARDS
    from amdockvs.molecules.library_stats import library_stats

    self.runtime._require_active_project()
    try:
        shards_root = self.runtime.get_project_resource_path(RESOURCE_SHARDS)
    except Exception:  # noqa: BLE001 — no folder: the size is left out
        shards_root = None
    return library_stats(self.runtime.workspace.project_db, shards_root)

shard_preps

shard_preps(shard_id: int) -> dict[str, tuple[int, int]]

One shard's preparations: family -> (prepared records, failed records).

Source code in src/amdockvs/molecules/api.py
520
521
522
523
524
525
526
527
528
529
def shard_preps(self, shard_id: int) -> dict[str, tuple[int, int]]:
    """One shard's preparations: family -> (prepared records, failed records)."""
    from sqlmodel import select

    from amdockvs.models import ShardPrep

    self.runtime._require_active_project()
    with self.runtime.workspace.project_db.get_session() as session:
        rows = session.exec(select(ShardPrep).where(ShardPrep.shard_id == int(shard_id))).all()
    return {str(row.family): (int(row.n_records), int(row.n_failed)) for row in rows}

select_fragment

select_fragment(molecule_id: int, fragment_index: int) -> Any

Make another component of the imported original the molecule's current structure.

Fragments are not stored: this one is cut again from the original and written alone. What was computed from the old structure goes (clear_derived); activities, measured on the imported compound, stay.

Source code in src/amdockvs/molecules/api.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
def select_fragment(self, molecule_id: int, fragment_index: int) -> Any:
    """Make another component of the imported original the molecule's current structure.

    Fragments are not stored: this one is cut again from the original and written alone. What
    was computed from the old structure goes (`clear_derived`); activities, measured on the
    imported compound, stay."""
    self.runtime._require_active_project()
    from amdockvs.chemistry.structures import molecule_mol, sdf_payload
    from amdockvs.core.payloads import payload_store
    from amdockvs.io.rows import identity_representations, structure_fields
    from amdockvs.molecules.fragments import fragments_of
    from amdockvs.project.deletion import clear_derived

    project_db = self.runtime.workspace.project_db
    molecule = self.get(molecule_id)
    if molecule is None:
        raise ValueError(f"Molecule {molecule_id} does not exist.")
    original = molecule_mol(project_db, {"stored_payload_id": molecule.stored_payload_id})
    if original is None:
        raise ValueError(f"Molecule {molecule_id} has no imported original to take a fragment from.")
    fragment = fragments_of(original).get(int(fragment_index))
    if fragment is None:
        raise ValueError(f"Fragment {fragment_index} does not exist for molecule {molecule_id}.")
    store = payload_store(project_db)
    clear_derived(project_db, [molecule.id])
    with project_db.get_session() as session:
        fragment_payload, = store.put(session, [sdf_payload(fragment)])
        row = session.get(MoleculeRecord, int(molecule.id))
        replaced = row.current_payload_id
        metadata = sanitize_molecule_extra_data(row.extra_data)
        if isinstance(metadata.get("fragmentation"), dict):  # a copy: in place, the JSON column sees no change
            metadata["fragmentation"] = {**metadata["fragmentation"], "selected_fragment_index": int(fragment_index)}
        for stale in ("chemistry", "history", "state"):  # described the structure that is gone
            metadata.pop(stale, None)
        row.extra_data = metadata
        row.current_payload_id = fragment_payload
        row.is_minimized = False
        fields = structure_fields(fragment)
        identity = {key: fields.pop(key) for key in ("inchikey", "canonical_smiles")}
        for key, value in fields.items():
            setattr(row, key, value)
        session.add(row)
        for representation in identity_representations(identity, molecule_id=int(row.id)):
            session.merge(MoleculeRepresentation(**representation))
        session.commit()
        session.refresh(row)
    if replaced:
        store.release([replaced])  # a no-op while it is still the import or a model's
    return row

Import

LoaderAPI dataclass

LoaderAPI(runtime: Any)

Methods:

Name Description
duplicate_imports

The files (resolved paths) imported completely into this project before.

download

Fetch ids from a download source (a key of amdockvs.io.downloads.SOURCES).

shard_ligands

The htpvs import: split the library into shards, materialize nothing.

duplicate_imports

duplicate_imports(files) -> list[str]

The files (resolved paths) imported completely into this project before.

Source code in src/amdockvs/io/api.py
100
101
102
103
104
105
def duplicate_imports(self, files) -> list[str]:
    """The files (resolved paths) imported completely into this project before."""
    from amdockvs.io.batches import duplicate_imports

    self.runtime._require_active_project()
    return duplicate_imports(self.runtime.workspace.project_db, files)

download

download(source, ids: Iterable[str], *, keep: bool = True, progress=None, cancel=None)

Fetch ids from a download source (a key of amdockvs.io.downloads.SOURCES). keep=False puts them in the project's temporary downloads: the import that reads them deletes them once it has completed. Returns an Outcome (files, failures).

Source code in src/amdockvs/io/api.py
123
124
125
126
127
128
129
130
131
def download(self, source, ids: Iterable[str], *, keep: bool = True, progress=None, cancel=None):
    """Fetch ``ids`` from a download ``source`` (a key of ``amdockvs.io.downloads.SOURCES``).
    ``keep=False`` puts them in the project's temporary downloads: the import that reads them
    deletes them once it has completed. Returns an ``Outcome`` (files, failures)."""
    from amdockvs.io import downloads

    source = downloads.SOURCES[source] if isinstance(source, str) else source
    folder = None if keep else downloads.temporary_folder(self.runtime.get_project_paths()["project_root"], source)
    return downloads.download(source, list(ids), folder=folder, progress=progress, cancel=cancel)

shard_ligands

shard_ligands(files: Iterable[PathLike], *, shard_size: int | None = None, executor_name: str = 'compute', depends_on: list[str] | None = None, molecule_kind: str = 'small_molecule', prefilter: Mapping[str, Any] | None = None, temporary_files: Iterable[PathLike] | None = None, force: bool = False) -> list[str]

The htpvs import: split the library into shards, materialize nothing.

Same feed as load_ligands — the byte-span splitter — with the record cap read as shard size. What changes is the worker: it writes the span back out as a file and registers a screening_shards row instead of parsing molecules into the project db.

Source code in src/amdockvs/io/api.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def shard_ligands(
    self,
    files: Iterable[PathLike],
    *,
    shard_size: int | None = None,
    executor_name: str = "compute",
    depends_on: list[str] | None = None,
    molecule_kind: str = "small_molecule",
    prefilter: Mapping[str, Any] | None = None,
    temporary_files: Iterable[PathLike] | None = None,
    force: bool = False,
) -> list[str]:
    """The `htpvs` import: split the library into shards, materialize nothing.

    Same feed as `load_ligands` — the byte-span splitter — with the record cap read as
    shard size. What changes is the worker: it writes the span back out as a file and
    registers a `screening_shards` row instead of parsing molecules into the project db.
    """
    normalized_files = normalize_files(files, label="ligand files")
    if not normalized_files:
        return []
    records = (
        default_shard_size(runtime=self.runtime)
        if shard_size is None
        else int(shard_size)
    )
    records = max(1, min(records, MAX_SHARD_RECORDS))
    params: dict[str, Any] = {
        "file_paths": [str(file_path) for file_path in normalized_files],
        **self._temporary(normalized_files, temporary_files),
        "batch_size": records,
        "molecule_kind": str(molecule_kind or "small_molecule"),
        **self._batches(normalized_files, force=force, kind=ImportKind.SHARDS, role="ligand"),
        "generation_id": self._import_generation_id(),  # opened after the batches: one duplicate opens none
    }
    if prefilter := _checked_prefilter(prefilter):
        params["prefilter"] = prefilter
    return [
        self._submit_job(
            shard_ligands_job,
            params=params,
            executor_name=executor_name,
            depends_on=depends_on,
            # ramp=False, like the feed: an over-declared total never completes.
            total_chunks=_total_import_chunks(normalized_files, batch_size=records, ramp=False),
            max_inflight_tasks=import_max_inflight(self.runtime),
        )
    ]

Chemistry

ChemistryAPI dataclass

ChemistryAPI(runtime: Any)

Methods:

Name Description
pkasso_gpu_support

Whether pKasso's Uni-pKa can run on this machine's GPU. Takes seconds the first time

run_ligand_pipeline

Run several chemistry steps in one pass over the active screening library.

run_shard_pipeline

The same steps as run_ligand_pipeline, over the shards of an htpvs project.

predict_receptors

Predict protein structures from sequence with the ESMFold API (thread executor).

pkasso_gpu_support

pkasso_gpu_support() -> GpuSupport

Whether pKasso's Uni-pKa can run on this machine's GPU. Takes seconds the first time for an installation (it starts PyTorch and CUDA there): not on a GUI thread.

Source code in src/amdockvs/chemistry/api.py
53
54
55
56
57
58
59
def pkasso_gpu_support(self) -> GpuSupport:
    """Whether pKasso's Uni-pKa can run on this machine's GPU. Takes seconds the first time
    for an installation (it starts PyTorch and CUDA there): not on a GUI thread."""
    status = protonation_tool_status(self.runtime, "pkasso")
    if not status.installed or status.command is None:
        return GpuSupport(False, "pKasso is not installed.")
    return pkasso_gpu_support(status.command)

run_ligand_pipeline

run_ligand_pipeline(steps: Sequence[str | tuple[str, dict[str, Any]]], *, ligands: MoleculeSetRef | MoleculeScope | int | None = None, structure_source: str = 'current', batch_size: int = 128, executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR, depends_on: list[str] | None = None, wait: bool = False) -> str | JobStatus

Run several chemistry steps in one pass over the active screening library.

run_ligand_pipeline(["standardize", "protonate", "generate_3d"]) reads and writes every ligand once; the three single-step jobs read and rewrite the whole library three times.

With no explicit row scope, a sharded library dispatches whole shards automatically. Passing ligands always selects the row adapter for curated/reference molecules.

Protonate and minimize steps are checked as their single-step methods check them (pH range, method and force-field names, tool installs). ponytail: the other steps' params go through as given and the worker raises.

Source code in src/amdockvs/chemistry/api.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def run_ligand_pipeline(
    self,
    steps: Sequence[str | tuple[str, dict[str, Any]]],
    *,
    ligands: MoleculeSetRef | MoleculeScope | int | None = None,
    structure_source: str = "current",
    batch_size: int = 128,
    executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR,
    depends_on: list[str] | None = None,
    wait: bool = False,
) -> str | JobStatus:
    """Run several chemistry steps in one pass over the active screening library.

    `run_ligand_pipeline(["standardize", "protonate", "generate_3d"])` reads and writes every
    ligand once; the three single-step jobs read and rewrite the whole library three times.

    With no explicit row scope, a sharded library dispatches whole shards automatically.
    Passing ``ligands`` always selects the row adapter for curated/reference molecules.

    Protonate and minimize steps are checked as their single-step methods check them (pH
    range, method and force-field names, tool installs). ponytail: the other steps' params go
    through as given and the worker raises.
    """
    normalized = normalize_steps(steps)
    if not normalized:
        raise ValueError("run_ligand_pipeline needs at least one step.")
    for name, _params in normalized:
        if name not in LIGAND_STEPS:
            raise ValueError(f"Unsupported ligand chemistry operation: {name}")
    normalized = [(name, self._step_params(name, params)) for name, params in normalized]
    if ligands is None:
        self.runtime._require_active_project()
        if has_shards(self.runtime.workspace.project_db):
            return self.run_shard_pipeline(
                normalized,
                executor_name=executor_name,
                depends_on=depends_on,
                wait=wait,
            )
    return self._submit_ligand_operation(
        [[name, params] for name, params in normalized],
        ligands=ligands,
        params={},
        structure_source=structure_source,
        batch_size=batch_size,
        executor_name=executor_name,
        depends_on=depends_on,
        wait=wait,
    )

run_shard_pipeline

run_shard_pipeline(steps: Sequence[str | tuple[str, dict[str, Any]]], *, params: dict[str, Any] | None = None, executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR, depends_on: list[str] | None = None, wait: bool = False) -> str | JobStatus

The same steps as run_ligand_pipeline, over the shards of an htpvs project.

One shard per chunk, one file in and one file out. The run writes into a new generation and only switches to it if it finishes, so a crashed run changes nothing and the retry simply starts over from the generation that is still the library.

Source code in src/amdockvs/chemistry/api.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def run_shard_pipeline(
    self,
    steps: Sequence[str | tuple[str, dict[str, Any]]],
    *,
    params: dict[str, Any] | None = None,
    executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR,
    depends_on: list[str] | None = None,
    wait: bool = False,
) -> str | JobStatus:
    """The same steps as `run_ligand_pipeline`, over the shards of an `htpvs` project.

    One shard per chunk, one file in and one file out. The run writes into a new
    generation and only switches to it if it finishes, so a crashed run changes nothing
    and the retry simply starts over from the generation that is still the library.
    """
    normalized = normalize_steps(steps)
    if not normalized:
        raise ValueError("run_shard_pipeline needs at least one step.")
    for name, _params in normalized:
        if name not in LIGAND_STEPS:
            raise ValueError(f"Unsupported ligand chemistry operation: {name}")
    normalized = [(name, self._step_params(name, params)) for name, params in normalized]
    if any(name == "conformers" for name, _params in normalized):
        raise ValueError(
            "Sharded conformer ensembles are not supported: one shard record currently "
            "stores one molecular structure. Generate conformers after materialization."
        )
    self.runtime._require_active_project()
    project_db = self.runtime.workspace.project_db
    # Opened here, before anything runs: the feed needs its output directory and the
    # result handler needs its id, and neither can invent one of its own without the two
    # disagreeing about where the generation lives.
    label = "+".join(name for name, _ in normalized)
    shards_root = Path(self.runtime.get_project_resource_path(RESOURCE_SHARDS))
    generation_id = create_generation(project_db, step=label, shard_dir=shards_root)
    job_id = self.runtime.submit_job(
        shard_chemistry_job,
        params=ShardChemistryJobParams(
            operation=[[name, step_params] for name, step_params in normalized],
            params=dict(params or {}),
            generation_id=generation_id,
            output_dir=str(shards_root / f"gen_{generation_id:04d}_{label}"),
        ).model_dump(mode="python"),
        executor_name=executor_name,
        depends_on=depends_on,
        priority=SHARDS_PRIORITY,
    )
    self.runtime.track_job_items(
        job_id, lambda: shard_generation_progress(project_db, generation_id), unit="ligands"
    )
    return self.runtime.wait_for_job(job_id) if wait else job_id

predict_receptors

predict_receptors(*, receptors: MoleculeSetRef | MoleculeScope | int | None = None, model: str = FAST_MODEL, force: bool = False, depends_on: list[str] | None = None, wait: bool = False) -> str | JobStatus

Predict protein structures from sequence with the ESMFold API (thread executor).

Only proteins without 3D by default; force=True predicts again and points the current structure to the new model. The token comes from ESM_API_KEY and is never stored.

Source code in src/amdockvs/chemistry/api.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
def predict_receptors(
        self,
        *,
        receptors: MoleculeSetRef | MoleculeScope | int | None = None,
        model: str = FAST_MODEL,
        force: bool = False,
        depends_on: list[str] | None = None,
        wait: bool = False,
) -> str | JobStatus:
    """Predict protein structures from sequence with the ESMFold API (thread executor).

    Only proteins without 3D by default; `force=True` predicts again and points the current structure
    to the new model. The token comes from ESM_API_KEY and is never stored.
    """
    self.runtime._require_active_project()
    if not api_token():
        raise RuntimeError(f"{ESM_TOKEN_ENV} is not set: paste your Biohub API token first.")
    receptor_set_ref = None if receptors is None or is_molecule_scope(receptors) else ensure_molecule_set_ref(self.runtime, receptors, name="chemistry_receptor_predict_input")
    receptor_scope = scope_payload(receptors) if is_molecule_scope(receptors) else {}
    receptor_filters = dict(receptor_scope.get("filters") or {})
    if "molecule_type" not in receptor_filters:
        receptor_filters["is_receptor"] = True
    if receptor_scope.get("limit") is not None:
        receptor_filters["_limit"] = receptor_scope.get("limit")
    params = ReceptorPredictionJobParams(
        model=model,
        force=bool(force),
        receptor_set_id=None if receptor_set_ref is None else int(receptor_set_ref.id),
        receptor_filters=receptor_filters if force else {**receptor_filters, "has_3d": False},
    )
    project_db = self.runtime.workspace.project_db
    total_items = db_count(project_db, prediction_scope_spec(params))
    # An empty scope with proteins in it means they all have 3D already. An empty scope with
    # no proteins at all may be an import still running: submit and let the job wait for it.
    if total_items == 0 and not force and db_count(project_db, prediction_scope_spec(params.model_copy(update={"receptor_filters": receptor_filters}))):
        raise ValueError("Every protein in scope already has a 3D structure; tick Force to predict again.")
    job_id = self.runtime.submit_job(
        receptor_prediction_job,
        params=params.model_dump(mode="python"),
        executor_name="thread",
        depends_on=depends_on,
        total_chunks=total_items or None,
    )
    if total_items:
        self.runtime.track_chunk_items(job_id, total_items, 1, unit="proteins")
    if wait:
        return self.runtime.wait_for_job(job_id)
    return job_id

Complexes

ComplexAPI dataclass

ComplexAPI(runtime: Any)

Methods:

Name Description
details

Load the complete Details-panel projection for a receptor-ligand pair.

details

details(complex_ref: ComplexRef | int) -> Details | None

Load the complete Details-panel projection for a receptor-ligand pair.

Source code in src/amdockvs/complexes/api.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def details(self, complex_ref: ComplexRef | int) -> Details | None:
    """Load the complete Details-panel projection for a receptor-ligand pair."""
    self.runtime._require_active_project()
    complex_id = int(complex_ref.id if isinstance(complex_ref, ComplexRef) else complex_ref)
    with self.runtime.workspace.project_db.get_session() as session:
        pair = session.get(ComplexRecord, complex_id)
        if pair is None:
            return None
        receptor = session.get(MoleculeRecord, int(pair.receptor_molecule_id or 0))
        ligand = session.get(MoleculeRecord, int(pair.ligand_molecule_id or 0))
        activity = (
            session.get(LigandActivity, int(pair.activity_id or 0))
            if int(pair.activity_id or 0) > 0
            else None
        )
    return self.Details(complex=pair, receptor=receptor, ligand=ligand, activity=activity)

QSAR

QSARAPI dataclass

QSARAPI(runtime: Any)

Bases: BuildMixin, PredictMixin, ModelAnalysisMixin, ResultsMixin, ActivitiesMixin

Methods:

Name Description
compute_descriptors

Submit the descriptor job. only_missing=True skips ligands that already have

compute_fingerprints

Submit a Morgan-fingerprint job (also fills physchem descriptors as a side effect).

compute_descriptors

compute_descriptors(*, molecule_set: MoleculeSetRef | MoleculeScope | int | None = None, only_missing: bool = True, batch_size: int = DEFAULT_LIGAND_BATCH_SIZE, executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR, depends_on: list[str] | None = None, compute_fingerprints: bool = False, fp_radius: int = 2, fp_nbits: int = 2048, alerts: bool = False, rdkit2d: bool = False, molecule_ids: list[int] | None = None) -> str

Submit the descriptor job. only_missing=True skips ligands that already have descriptors computed (MoleculeRecord.mw populated). With compute_fingerprints=True it also stores a Morgan fingerprint per ligand, and only_missing then means "lacks that fingerprint" so FPs can be added to already-described ligands. rdkit2d=True also stores the full RDKit 2D block the models train on (only_missing: lacks that block). With alerts=True it is the alerts job instead: PAINS and identity keys, which a library import leaves out. molecule_ids narrows the scope to those molecules.

Source code in src/amdockvs/qsar/api.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def compute_descriptors(
    self,
    *,
    molecule_set: MoleculeSetRef | MoleculeScope | int | None = None,
    only_missing: bool = True,
    batch_size: int = DEFAULT_LIGAND_BATCH_SIZE,
    executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR,
    depends_on: list[str] | None = None,
    compute_fingerprints: bool = False,
    fp_radius: int = 2,
    fp_nbits: int = 2048,
    alerts: bool = False,
    rdkit2d: bool = False,
    molecule_ids: list[int] | None = None,
) -> str:
    """Submit the descriptor job. only_missing=True skips ligands that already have
    descriptors computed (MoleculeRecord.mw populated). With compute_fingerprints=True it
    also stores a Morgan fingerprint per ligand, and only_missing then means "lacks that
    fingerprint" so FPs can be added to already-described ligands. rdkit2d=True also stores
    the full RDKit 2D block the models train on (only_missing: lacks that block). With
    alerts=True it is the alerts job instead: PAINS and identity keys, which a library import
    leaves out. molecule_ids narrows the scope to those molecules."""
    self.runtime._require_active_project()
    molecule_set_ref = (
        None
        if molecule_set is None or is_molecule_scope(molecule_set)
        else ensure_molecule_set_ref(self.runtime, molecule_set, name="qsar_descriptor_input")
    )
    molecule_scope = scope_payload(molecule_set) if is_molecule_scope(molecule_set) else {}
    filters = apply_workflow_filters(
        {**dict(molecule_scope.get("filters") or {}), "excluded": False},
        workflow=QSAR_WORKFLOW,
        role="ligand",
    )
    params = DescriptorJobParams(
        batch_size=batch_size,
        molecule_set_id=None if molecule_set_ref is None else int(molecule_set_ref.id),
        molecule_filters=filters,
        only_missing=bool(only_missing),
        compute_fingerprints=bool(compute_fingerprints),
        fp_radius=int(fp_radius),
        fp_nbits=int(fp_nbits),
        alerts=bool(alerts),
        rdkit2d=bool(rdkit2d),
        molecule_ids=None if molecule_ids is None else [int(i) for i in molecule_ids],
    )
    return self.runtime.submit_job(
        calculate_molecule_alerts_job if alerts else calculate_molecule_descriptors_job,
        params=params.model_dump(mode="python"),
        executor_name=executor_name,
        depends_on=depends_on,
    )

compute_fingerprints

compute_fingerprints(*, molecule_set: MoleculeSetRef | MoleculeScope | int | None = None, only_missing: bool = True, radius: int = 2, nbits: int = 2048, batch_size: int = DEFAULT_LIGAND_BATCH_SIZE, executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR, depends_on: list[str] | None = None) -> str

Submit a Morgan-fingerprint job (also fills physchem descriptors as a side effect).

Source code in src/amdockvs/qsar/api.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def compute_fingerprints(
    self,
    *,
    molecule_set: MoleculeSetRef | MoleculeScope | int | None = None,
    only_missing: bool = True,
    radius: int = 2,
    nbits: int = 2048,
    batch_size: int = DEFAULT_LIGAND_BATCH_SIZE,
    executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR,
    depends_on: list[str] | None = None,
) -> str:
    """Submit a Morgan-fingerprint job (also fills physchem descriptors as a side effect)."""
    return self.compute_descriptors(
        molecule_set=molecule_set,
        only_missing=only_missing,
        batch_size=batch_size,
        executor_name=executor_name,
        depends_on=depends_on,
        compute_fingerprints=True,
        fp_radius=radius,
        fp_nbits=nbits,
    )

Binding sites

BindingSiteAPI dataclass

BindingSiteAPI(runtime: Any)

Methods:

Name Description
select

Build a lazy binding-site selection.

delete_sites

Deletes sites by id. The counterpart of prediction being additive.

save_site

Saves a site. Without binding_site_id it creates a new one; with it, rewrites that one.

reference_ligands

(id, name) of the reference ligands that came with this receptor's structure: the

suggest_box_from_ligand

Auto box from a reference ligand: center = its centroid, size = cubic box

active_site_id

The id of the molecule's active site, None without one.

select

select(*, molecule_id: int | None = None, source: str | None = None, run_id: str | None = None, limit: int | None = None) -> Selection[BindingSite]

Build a lazy binding-site selection.

Source code in src/amdockvs/binding_sites/api.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def select(
    self,
    *,
    molecule_id: int | None = None,
    source: str | None = None,
    run_id: str | None = None,
    limit: int | None = None,
) -> Selection[BindingSite]:
    """Build a lazy binding-site selection."""
    self.runtime._require_active_project()
    return self._selection(BindingSiteScope(
        molecule_id=None if molecule_id is None else int(molecule_id),
        source=str(source) if source is not None else None,
        run_id=str(run_id) if run_id is not None else None,
        limit=None if limit is None else max(0, int(limit)),
    ))

delete_sites

delete_sites(binding_site_ids: Iterable[int]) -> int

Deletes sites by id. The counterpart of prediction being additive.

Source code in src/amdockvs/binding_sites/api.py
331
332
333
334
335
336
def delete_sites(self, binding_site_ids: Iterable[int]) -> int:
    """Deletes sites by id. The counterpart of prediction being additive."""
    self.runtime._require_active_project()
    from amdockvs.project.deletion import delete_binding_sites

    return delete_binding_sites(self.runtime.workspace.project_db, binding_site_ids)

save_site

save_site(*, molecule_id: int, name: str = '', source: str = 'manual', source_ref: str = '', center: tuple[float, float, float], size: tuple[float, float, float], binding_site_id: int | None = None, set_active: bool = False, extra_data: dict[str, Any] | None = None) -> BindingSite

Saves a site. Without binding_site_id it creates a new one; with it, rewrites that one.

Source code in src/amdockvs/binding_sites/api.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
def save_site(
        self,
        *,
        molecule_id: int,
        name: str = "",
        source: str = "manual",
        source_ref: str = "",
        center: tuple[float, float, float],
        size: tuple[float, float, float],
        binding_site_id: int | None = None,
        set_active: bool = False,
        extra_data: dict[str, Any] | None = None,
) -> BindingSite:
    """Saves a site. Without `binding_site_id` it creates a new one; with it, rewrites that one."""
    self.runtime._require_active_project()
    if (problem := box_error(center, size)) is not None:
        raise ValueError(problem)
    with self.runtime.workspace.project_db.get_session() as session:
        molecule = session.get(MoleculeRecord, int(molecule_id))
        if molecule is None:
            raise ValueError(f"Molecule {molecule_id} does not exist.")
        site = None if binding_site_id is None else session.get(BindingSite, int(binding_site_id))
        if site is None:
            site = BindingSite(molecule_id=int(molecule_id))
        elif int(site.molecule_id) != int(molecule_id):
            raise ValueError(
                f"Binding site {binding_site_id} belongs to molecule {site.molecule_id}."
            )
        site.name = str(name or "")
        site.source = str(source or "manual")
        site.source_ref = str(source_ref or "")
        site.center_x = float(center[0])
        site.center_y = float(center[1])
        site.center_z = float(center[2])
        site.size_x = float(size[0])
        site.size_y = float(size[1])
        site.size_z = float(size[2])
        site.extra_data = dict(extra_data or {})
        session.add(site)
        session.flush()
        if set_active:
            set_active_site_row(session, int(molecule_id), int(site.id))
        session.commit()
        session.refresh(site)
        return site

reference_ligands

reference_ligands(receptor_id: int) -> list[tuple[int, str]]

(id, name) of the reference ligands that came with this receptor's structure: the co-crystal ligands its import paired with it. Library (screening) ligands never are, so this is the short, meaningful list to build a box from.

Source code in src/amdockvs/binding_sites/api.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def reference_ligands(self, receptor_id: int) -> list[tuple[int, str]]:
    """(id, name) of the reference ligands that came with this receptor's structure: the
    co-crystal ligands its import paired with it. Library (screening) ligands never are,
    so this is the short, meaningful list to build a box from."""
    self.runtime._require_active_project()
    statement = (
        select(MoleculeRecord.id, MoleculeRecord.name)
        .join(ComplexRecord, ComplexRecord.ligand_molecule_id == MoleculeRecord.id)
        .where(ComplexRecord.receptor_molecule_id == int(receptor_id),
               ComplexRecord.purpose == ComplexPurpose.REFERENCE)
        .order_by(MoleculeRecord.id)
    )
    with self.runtime.workspace.project_db.get_session() as session:
        return [(int(mid), str(name or "")) for mid, name in session.exec(statement).all()]

suggest_box_from_ligand

suggest_box_from_ligand(*, ligand_id: int, scale: float | None = None, padding: float | None = None) -> dict[str, Any]

Auto box from a reference ligand: center = its centroid, size = cubic box derived from the ligand's radius of gyration. Returns {center, size, rg}.

scale/padding default to the configured geometry (settings > binding_sites).

Source code in src/amdockvs/binding_sites/api.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
def suggest_box_from_ligand(
        self,
        *,
        ligand_id: int,
        scale: float | None = None,
        padding: float | None = None,
) -> dict[str, Any]:
    """Auto box from a reference ligand: center = its centroid, size = cubic box
    derived from the ligand's radius of gyration. Returns {center, size, rg}.

    `scale`/`padding` default to the configured geometry (settings > binding_sites)."""
    self.runtime._require_active_project()
    with self.runtime.workspace.project_db.get_session() as session:
        ligand = session.get(MoleculeRecord, int(ligand_id))
        if ligand is None:
            raise ValueError(f"Molecule {ligand_id} does not exist.")
        payload_id = molecule_payload_id(ligand)
    if payload_id is None:
        raise ValueError(f"Ligand {ligand_id} has no stored structure.")
    coords = _read_atom_coords(*read_structure(self.runtime, payload_id))
    if not coords:
        raise ValueError(f"No atom coordinates found in ligand {ligand_id}.")
    geometry = app_config(self.runtime).binding_sites
    return box_from_coords(
        coords,
        scale=geometry.box_scale if scale is None else float(scale),
        padding=geometry.box_padding if padding is None else float(padding),
        minimum=geometry.box_min_edge,
        maximum=geometry.box_max_edge,
    )

active_site_id

active_site_id(molecule_id: int) -> int | None

The id of the molecule's active site, None without one.

Source code in src/amdockvs/binding_sites/api.py
523
524
525
526
527
528
529
530
531
def active_site_id(self, molecule_id: int) -> int | None:
    """The id of the molecule's active site, None without one."""
    self.runtime._require_active_project()
    with self.runtime.workspace.project_db.get_session() as session:
        return session.exec(
            select(BindingSite.id)
            .where(BindingSite.molecule_id == int(molecule_id))
            .where(BindingSite.is_active == True)  # noqa: E712 - SQL expression
        ).first()

Docking

DockingAPI dataclass

DockingAPI(runtime: Any)

Methods:

Name Description
check_protocol

Check the program's current configuration without deleting or submitting anything.

stored_protocol_hash

The hash a run of this configuration will dock and skip under (check_protocol keeps an

live_campaign_progress

Ligands/docked/state of these receptors for one program ("" = summed over all).

recoverable_ranked_runs

Interrupted top-N campaigns recoverable from completed result shards.

select_hits

Select a recomputable Top-N from the durable HTP result dataset.

recover_ranked_hits

Materialize the best available N without submitting docking work.

preparation_summary

Return total/ready/failed preparation counts for a molecule scope.

unprepared_molecules_clause

Opaque SmartTable clause selecting molecules not ready for every engine family.

receptor_setup_clause

SmartTable clause for receptors needing preparation or an active search box.

delete_results

Delete results, their interactions and files. with_siblings: every pose of the same

pairs_per_task

Pairs per docking task: batch_size when a caller gives one, else the program's own

autobatch

Tasks a docking job starts at, in its chunks, when the executor sizes them: the

prepare_ligand_shards

prepare_ligands for a sharded library: the unit of work is a shard, not a row.

run_shards

run for a sharded library: the campaign, with the gate that makes it end.

set_grid

Save a box as the receptor's active site. A box drawn around a reference ligand says

method_misfit_receptor_ids

Receptors whose active box does not fit the docking method (methods.py).

list_box_residues

Residues with at least one atom inside the receptor's active binding-site box.

check_receptors

Receptor-only half of check_required: preparation + grid status, no ligand scan.

run

Run docking over the active library, selecting its row or shard adapter.

move_to_queue

Continue a docking run over rows on a cluster's queue: it is stopped here (waited for,

has_results

Whether the project has docking results or completed screening fragments.

ligand_summaries

(best pose, pose count) per ligand, one page at a time.

compute_diagrams

Render 2D interaction diagrams for docking poses as a standalone job.

diagram_path

Convention path for a pose's diagram (may not exist yet).

count_docked_pairs

program counts only the pairs docked against what its run would dock now: each

check_protocol

check_protocol(*, program: str, engine_config: dict, protocol_metadata: dict | None = None, replace_existing: bool = False) -> dict

Check the program's current configuration without deleting or submitting anything.

Source code in src/amdockvs/docking/api.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def check_protocol(
    self, *, program: str, engine_config: dict, protocol_metadata: dict | None = None,
    replace_existing: bool = False,
) -> dict:
    """Check the program's current configuration without deleting or submitting anything."""
    if not isinstance(replace_existing, bool):
        raise ValueError("replace_existing must be a boolean.")
    project_db = self._project_db()
    spec = self.get_program_spec(program)
    protocol = resolved_protocol(spec, spec.validate_config(engine_config), protocol_metadata)
    check_protocol_conflict(
        project_db, program=spec, protocol=protocol,
        replace_existing=replace_existing,
    )
    return protocol

stored_protocol_hash

stored_protocol_hash(*, program: str, protocol_hash: str) -> str

The hash a run of this configuration will dock and skip under (check_protocol keeps an older project's hash for an unchanged configuration), without checking for a conflict.

Source code in src/amdockvs/docking/api.py
191
192
193
194
195
def stored_protocol_hash(self, *, program: str, protocol_hash: str) -> str:
    """The hash a run of this configuration will dock and skip under (`check_protocol` keeps an
    older project's hash for an unchanged configuration), without checking for a conflict."""
    return stored_protocol_hash(
        self._project_db(), program=self.get_program_spec(program), protocol_hash=str(protocol_hash or ""))

live_campaign_progress

live_campaign_progress(*, job_ids: list[str] | tuple[str, ...] = (), receptor_ids: list[int] | tuple[int, ...] = (), protocol_hash: str = '') -> dict[int, dict[str, Any]]

Ligands/docked/state of these receptors for one program ("" = summed over all).

Source code in src/amdockvs/docking/api.py
197
198
199
200
201
202
203
204
205
206
207
208
209
def live_campaign_progress(
    self,
    *,
    job_ids: list[str] | tuple[str, ...] = (),
    receptor_ids: list[int] | tuple[int, ...] = (),
    protocol_hash: str = "",
) -> dict[int, dict[str, Any]]:
    """Ligands/docked/state of these receptors for one program ("" = summed over all)."""
    self.runtime._require_active_project()
    # ponytail: the engine does not list the chunks a job has in flight, so the totals count
    # what is written; `job_ids` comes back when it does.
    cells = receptor_progress(self.runtime.workspace.project_db, receptor_ids, protocol_hash)
    return {receptor_id: {**values, "docked": values.pop("progress")} for receptor_id, values in cells.items()}

recoverable_ranked_runs

recoverable_ranked_runs() -> list[dict[str, Any]]

Interrupted top-N campaigns recoverable from completed result shards.

Source code in src/amdockvs/docking/api.py
211
212
213
214
215
216
217
def recoverable_ranked_runs(self) -> list[dict[str, Any]]:
    """Interrupted top-N campaigns recoverable from completed result shards."""
    context = self.runtime._require_active_project()
    return recoverable_ranked_runs(
        self.runtime.workspace.project_db,
        project_root=context.path,
    )

select_hits

select_hits(*, run_id: str, protocol_hash: str, filters: dict[str, Any] | None = None, top_n: int) -> list[dict[str, Any]]

Select a recomputable Top-N from the durable HTP result dataset.

Source code in src/amdockvs/docking/api.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def select_hits(
    self,
    *,
    run_id: str,
    protocol_hash: str,
    filters: dict[str, Any] | None = None,
    top_n: int,
) -> list[dict[str, Any]]:
    """Select a recomputable Top-N from the durable HTP result dataset."""
    context = self.runtime._require_active_project()
    return select_shard_hits(
        self.runtime.workspace.project_db,
        project_root=context.path,
        run_id=run_id,
        protocol_hash=protocol_hash,
        filters=filters,
        top_n=top_n,
    )

recover_ranked_hits

recover_ranked_hits(*, run_id: str, protocol_hash: str, top_n: int, threshold: float = 0.0) -> dict[str, int]

Materialize the best available N without submitting docking work.

Source code in src/amdockvs/docking/api.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def recover_ranked_hits(
    self,
    *,
    run_id: str,
    protocol_hash: str,
    top_n: int,
    threshold: float = 0.0,
) -> dict[str, int]:
    """Materialize the best available N without submitting docking work."""
    context = self.runtime._require_active_project()
    return recover_ranked_hits(
        self.runtime.workspace.project_db,
        project_root=context.path,
        run_id=run_id,
        protocol_hash=protocol_hash,
        top_n=top_n,
        threshold=threshold,
    )

preparation_summary

preparation_summary(scope: MoleculeScope, *, role_type: str, engine: str = 'ad4') -> dict[str, int]

Return total/ready/failed preparation counts for a molecule scope.

Source code in src/amdockvs/docking/api.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def preparation_summary(
        self,
        scope: MoleculeScope,
        *,
        role_type: str,
        engine: str = "ad4",
) -> dict[str, int]:
    """Return total/ready/failed preparation counts for a molecule scope."""
    self.runtime._require_active_project()
    normalized_role = str(role_type or "").strip().lower()
    normalized_engine = str(engine or "ad4").strip().lower()
    if normalized_role not in {"ligand", "receptor"}:
        raise ValueError("role_type must be 'ligand' or 'receptor'.")
    # Count each side alone first: a family with no state row of that kind anywhere needs
    # no join with the scope (the common case before the first preparation).
    molecules = self.runtime.molecules
    project_db = self.runtime.workspace.project_db
    flags = {"is_ligand" if normalized_role == "ligand" else "is_receptor": True, "prepared_engine_key": normalized_engine}

    def in_scope(ready: bool) -> int:
        states = prepared_molecules_spec(role_type=normalized_role, engine=normalized_engine, is_ready=ready)
        if not db_count(project_db, states):
            return 0
        return molecules.count(molecules.filter(scope, filters={**flags, "prepared": ready}))

    total = molecules.count(scope)
    return {"total": total, "ready": in_scope(True) if total else 0, "failed": in_scope(False) if total else 0}

unprepared_molecules_clause

unprepared_molecules_clause(*, role_type: str, engines: list[str] | tuple[str, ...])

Opaque SmartTable clause selecting molecules not ready for every engine family.

Source code in src/amdockvs/docking/api.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def unprepared_molecules_clause(self, *, role_type: str, engines: list[str] | tuple[str, ...]):
    """Opaque SmartTable clause selecting molecules not ready for every engine family."""
    self.runtime._require_active_project()
    role = str(role_type or "").strip().lower()
    if role not in {"ligand", "receptor"}:
        raise ValueError("role_type must be 'ligand' or 'receptor'.")
    normalized_engines = tuple(
        dict.fromkeys(str(value or "").strip().lower() for value in engines if str(value or "").strip()))
    project_db = self.runtime.workspace.project_db
    if any(
        not db_count(project_db, prepared_molecules_spec(role_type=role, engine=engine))
        for engine in normalized_engines
    ):
        return None  # a family nothing is ready for leaves every row in: no anti-join to run
    # NOT IN, not a correlated NOT EXISTS: DuckDB (1 thread, 1 GB) hash-joins the whole
    # table for the latter (4 s and GBs of spill for one page); SQLite is faster with it too.
    model, molecule_column, payload_column = prep_table(role)
    missing = [
        MoleculeRecord.id.not_in(
            select(molecule_column).where(model.family == engine, payload_column.is_not(None))
        )
        for engine in normalized_engines
    ]
    if not missing:
        return None
    return missing[0] if len(missing) == 1 else or_(*missing)

receptor_setup_clause

receptor_setup_clause(*, engines: list[str] | tuple[str, ...])

SmartTable clause for receptors needing preparation or an active search box.

Source code in src/amdockvs/docking/api.py
312
313
314
315
316
317
318
319
320
321
def receptor_setup_clause(self, *, engines: list[str] | tuple[str, ...]):
    """SmartTable clause for receptors needing preparation or an active search box."""
    unprepared = self.unprepared_molecules_clause(role_type="receptor", engines=engines)
    if unprepared is None:
        return None
    defined_boxes = select(BindingSite.molecule_id).where(
        BindingSite.is_active == True,  # noqa: E712
        *defined_box_clauses(),
    )
    return or_(unprepared, MoleculeRecord.id.not_in(defined_boxes))

delete_results

delete_results(result_ids: list[int] | tuple[int, ...], *, with_siblings: bool = False) -> int

Delete results, their interactions and files. with_siblings: every pose of the same receptor, ligand, protocol and run as each id goes too — what a Results ligand row (its best pose) stands for.

Source code in src/amdockvs/docking/api.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def delete_results(self, result_ids: list[int] | tuple[int, ...], *, with_siblings: bool = False) -> int:
    """Delete results, their interactions and files. `with_siblings`: every pose of the same
    receptor, ligand, protocol and run as each id goes too — what a Results ligand row
    (its best pose) stands for."""
    self.runtime._require_active_project()
    from amdockvs.project.deletion import delete_docking_results, delete_results_where

    project_db = self.runtime.workspace.project_db
    if not with_siblings:
        return delete_docking_results(project_db, result_ids)
    from sqlalchemy.orm import aliased

    from amdockvs.models import DockingResultRecord

    seed = aliased(DockingResultRecord)
    return delete_results_where(project_db, exists().where(
        seed.id.in_([int(i) for i in result_ids]),
        seed.receptor_molecule_id == DockingResultRecord.receptor_molecule_id,
        seed.ligand_molecule_id == DockingResultRecord.ligand_molecule_id,
        seed.docking_run_id == DockingResultRecord.docking_run_id,
    ))

pairs_per_task

pairs_per_task(program_spec: DockingProgramSpec, batch_size: int | None = None) -> int

Pairs per docking task: batch_size when a caller gives one, else the program's own setting (docking.<engine>.batch_size).

Source code in src/amdockvs/docking/api.py
349
350
351
352
353
def pairs_per_task(self, program_spec: DockingProgramSpec, batch_size: int | None = None) -> int:
    """Pairs per docking task: `batch_size` when a caller gives one, else the program's own
    setting (`docking.<engine>.batch_size`)."""
    config = getattr(app_config(self.runtime).docking, program_spec.docking_engine, None)
    return max(1, int(batch_size or getattr(config, "batch_size", 0) or DEFAULT_DOCKING_BATCH_SIZE))

autobatch

autobatch(program_spec: DockingProgramSpec, batch_size: int | None = None) -> int

Tasks a docking job starts at, in its chunks, when the executor sizes them: the program's docking.<engine>.autobatch pairs, never under one chunk; 0 when it has none.

Source code in src/amdockvs/docking/api.py
355
356
357
358
359
360
def autobatch(self, program_spec: DockingProgramSpec, batch_size: int | None = None) -> int:
    """Tasks a docking job starts at, in its chunks, when the executor sizes them: the
    program's `docking.<engine>.autobatch` pairs, never under one chunk; 0 when it has none."""
    config = getattr(app_config(self.runtime).docking, program_spec.docking_engine, None)
    pairs = int(getattr(config, "autobatch", 0) or 0)
    return max(1, pairs // self.pairs_per_task(program_spec, batch_size)) if pairs else 0

prepare_ligand_shards

prepare_ligand_shards(*, program: str = key, force: bool = False, shard_ids: list[int] | None = None, executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR, depends_on: list[str] | None = None) -> str

prepare_ligands for a sharded library: the unit of work is a shard, not a row.

shard_ids narrows it to those shards (the Shards table selection); None = every shard. One shard is one task.

Source code in src/amdockvs/docking/api.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
def prepare_ligand_shards(
        self,
        *,
        program: str = VINA_PROGRAM.key,
        force: bool = False,
        shard_ids: list[int] | None = None,
        executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR,
        depends_on: list[str] | None = None,
) -> str:
    """`prepare_ligands` for a sharded library: the unit of work is a shard, not a row.

    `shard_ids` narrows it to those shards (the Shards table selection); None = every
    shard. One shard is one task.
    """
    self.runtime._require_active_project()
    program_spec = self.get_program_spec(program)
    if not program_spec.requires_ligand_preparation:
        raise ValueError(f"Docking program '{program_spec.key}' does not require ligand preparation.")
    if not program_spec.supports_shards:
        raise ValueError(f"Docking program '{program_spec.key}' does not support sharded libraries.")
    params = PrepareLigandShardsJobParams(
        engine=program_spec.preparation_engine,
        force=force,
        shard_ids=None if shard_ids is None else [int(value) for value in shard_ids],
    )
    return self.runtime.submit_job(
        prepare_ligand_shards_job,
        params=params.model_dump(mode="python"),
        executor_name=executor_name,
        depends_on=depends_on,
        priority=SHARDS_PRIORITY,
    )

run_shards

run_shards(*, program: str = key, receptor_set: MoleculeSetRef | MoleculeScope | int | None = None, hit_threshold: float, hit_cap: int, output_dir: PathLike | None = None, exhaustiveness: int = 8, num_modes: int = 9, box_center: tuple[float, float, float] | None = None, box_size: tuple[float, float, float] | None = None, scoring_function: str = 'vina', vina_command: str = DEFAULT_VINA_COMMAND, vina_cpu: int = 1, seed: int = 0, spacing: float = 0.375, energy_range: float = 3.0, min_rmsd: float = 1.0, run_id: str | None = None, protocol_metadata: dict | None = None, engine_config: dict[str, Any] | None = None, executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR, depends_on: list[str] | None = None, skip_existing: bool = True, payload: str = PAYLOAD_LIGHT, check_required: bool = True, selected_from_receptor_id: int | None = None, selected_top_n: int | None = None, replace_existing: bool = False, off_target_set: MoleculeSetRef | MoleculeScope | int | None = None) -> str

run for a sharded library: the campaign, with the gate that makes it end.

No ligand scope — the library is the inventory of prepared shards. When the run ends, the best hit_cap ligands per receptor that pass the hit_threshold prefilter become rows; both are required, not defaulted: a campaign without them writes back everything it scored, which is the failure mode htpvs exists to prevent. A dependent off-target stage sets selected_from_receptor_id; its deferred chunker reads that receptor's durable Top-N and extracts only those records from the source shards.

On a cluster's queue (executor_name of kind queue) the whole of it is one job of the queue (amdockvs.docking.campaign): with off_target_set, the best hit_cap of the one receptor of receptor_set are docked against those receptors there too, and no dependent stage is submitted here.

Source code in src/amdockvs/docking/api.py
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
def run_shards(
        self,
        *,
        program: str = VINA_PROGRAM.key,
        receptor_set: MoleculeSetRef | MoleculeScope | int | None = None,
        hit_threshold: float,
        hit_cap: int,
        output_dir: PathLike | None = None,
        exhaustiveness: int = 8,
        num_modes: int = 9,
        box_center: tuple[float, float, float] | None = None,
        box_size: tuple[float, float, float] | None = None,
        scoring_function: str = "vina",
        vina_command: str = DEFAULT_VINA_COMMAND,
        vina_cpu: int = 1,
        seed: int = 0,
        spacing: float = 0.375,
        energy_range: float = 3.0,
        min_rmsd: float = 1.0,
        run_id: str | None = None,
        protocol_metadata: dict | None = None,
        engine_config: dict[str, Any] | None = None,
        executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR,
        depends_on: list[str] | None = None,
        skip_existing: bool = True,
        payload: str = PAYLOAD_LIGHT,
        check_required: bool = True,
        selected_from_receptor_id: int | None = None,
        selected_top_n: int | None = None,
        replace_existing: bool = False,
        off_target_set: MoleculeSetRef | MoleculeScope | int | None = None,
) -> str:
    """`run` for a sharded library: the campaign, with the gate that makes it end.

    No ligand scope — the library is the inventory of prepared shards. When the run ends, the
    best `hit_cap` ligands per receptor that pass the `hit_threshold` prefilter become rows;
    both are required, not defaulted: a campaign without them writes back everything it
    scored, which is the failure mode `htpvs` exists to prevent. A dependent off-target
    stage sets `selected_from_receptor_id`; its deferred chunker reads that receptor's
    durable Top-N and extracts only those records from the source shards.

    On a cluster's queue (`executor_name` of kind `queue`) the whole of it is one job of the
    queue (`amdockvs.docking.campaign`): with `off_target_set`, the best `hit_cap` of the one
    receptor of `receptor_set` are docked against those receptors there too, and no
    dependent stage is submitted here.
    """
    self.runtime._require_active_project()
    queue = self.runtime.is_queue(executor_name)
    if off_target_set is not None and not queue:
        raise ValueError("off_target_set is for a cluster's queue; here the off-target stage is its own run "
                         "(selected_from_receptor_id).")
    if queue and (depends_on or selected_from_receptor_id is not None):
        raise ValueError("A campaign on a cluster's queue runs its off-target stage itself: use off_target_set.")
    if selected_top_n is not None and selected_from_receptor_id is None:
        raise ValueError("selected_top_n requires selected_from_receptor_id.")
    if selected_from_receptor_id is not None and not str(run_id or "").strip():
        raise ValueError("Off-target selection requires the reference run_id.")
    if (box_center is None) ^ (box_size is None):
        raise ValueError("docking.run requires both box_center and box_size when either one is provided.")
    if box_center is not None and (problem := box_error(box_center, box_size)) is not None:
        raise ValueError(problem)
    program_spec = self.get_program_spec(program)
    if not program_spec.supports_shards:
        raise ValueError(f"Docking program '{program_spec.key}' does not support sharded libraries.")
    knobs = dict(
        exhaustiveness=exhaustiveness,
        num_modes=num_modes,
        scoring_function=scoring_function,
        vina_command=vina_command,
        vina_cpu=vina_cpu,
        seed=seed,
        spacing=spacing,
        energy_range=energy_range,
        min_rmsd=min_rmsd,
    )
    resolved_engine_config = _validated_engine_config(program_spec, engine_config, **knobs)
    protocol_metadata = self.check_protocol(
        program=program_spec.key, engine_config=resolved_engine_config,
        protocol_metadata=protocol_metadata, replace_existing=replace_existing,
    )
    reset_results = replace_existing and check_protocol_conflict(
        self.runtime.workspace.project_db, program=program_spec, protocol=protocol_metadata, replace_existing=True,
    )
    if reset_results and selected_from_receptor_id is not None:
        raise ValueError("Changing docking configuration requires rerunning the reference stage before off-target docking.")
    receptor_set_ref = self._set_ref(receptor_set, name="docking_receptor_input")
    receptor_scope = scope_payload(receptor_set) if is_molecule_scope(receptor_set) else {}
    receptor_filters = self._program_scope_filters(receptor_scope, role="receptor", program=program_spec)
    params = DockShardsJobParams(
        output_dir=self._output_dir(output_dir),
        engine=program_spec.docking_engine,
        preparation_engine=program_spec.preparation_engine,
        receptor_set_id=None if receptor_set_ref is None else int(receptor_set_ref.id),
        receptor_filters=receptor_filters,
        box_center=box_center,
        box_size=box_size,
        **_engine_fields(resolved_engine_config, knobs),
        run_id=str(run_id or uuid4().hex),
        protocol_metadata=DockingProtocolMetadata.from_mapping(protocol_metadata or {}),
        engine_config=resolved_engine_config,
        hit_threshold=float(hit_threshold),
        hit_cap=int(hit_cap),
        payload=str(payload),
        selected_from_receptor_id=selected_from_receptor_id,
        selected_top_n=(int(selected_top_n) if selected_top_n is not None else int(hit_cap)),
        skip_existing=skip_existing,
        check_required=check_required,
    )
    if reset_results:
        if check_required and not depends_on:
            dock_shards_job.count_chunks(
                params.model_dump(mode="python"), config={"project_db": self.runtime.workspace.project_db},
            )
        clear_previous_docking(self.runtime.workspace.project_db, program=program_spec)
    cpu = program_spec.resource_requirements(resolved_engine_config)["cpu_required"]
    if queue:
        off_ref = self._set_ref(off_target_set, name="docking_off_target_input")
        off_scope = scope_payload(off_target_set) if is_molecule_scope(off_target_set) else {}
        campaign_params = DockCampaignParams(
            **params.model_dump(mode="python"),
            off_receptor_set_id=None if off_ref is None else int(off_ref.id),
            off_receptor_filters=self._program_scope_filters(off_scope, role="receptor", program=program_spec)
            if off_target_set is not None else {},
            cpu_required=cpu,
        )
        return self.runtime.submit_campaign(dock_shards_campaign, params=campaign_params.model_dump(mode="python"),
                                            executor_name=executor_name, priority=SHARDS_PRIORITY)
    return self.runtime.submit_job(
        dock_shards_job,
        queue_behind="docking",
        params=params.model_dump(mode="python"),
        executor_name=executor_name,
        depends_on=depends_on,
        priority=SHARDS_PRIORITY,
        cpu_required=cpu,
    )

set_grid

set_grid(*, receptor_id: int, center: tuple[float, float, float], size: tuple[float, float, float], spacing: float = 0.375, engine: str = 'vina', metadata: dict[str, Any] | None = None, name: str = 'Manual Site', source: str = 'manual', source_ref: str = '') -> dict[str, Any]

Save a box as the receptor's active site. A box drawn around a reference ligand says so (source="ligand", source_ref=str(ligand_id), e.g. name="SAR405 site"), as the sites found at import do; the default is a manual one.

Source code in src/amdockvs/docking/api.py
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
def set_grid(
        self,
        *,
        receptor_id: int,
        center: tuple[float, float, float],
        size: tuple[float, float, float],
        spacing: float = 0.375,
        engine: str = "vina",
        metadata: dict[str, Any] | None = None,
        name: str = "Manual Site",
        source: str = "manual",
        source_ref: str = "",
) -> dict[str, Any]:
    """Save a box as the receptor's active site. A box drawn around a reference ligand says
    so (`source="ligand"`, `source_ref=str(ligand_id)`, e.g. `name="SAR405 site"`), as the
    sites found at import do; the default is a manual one."""
    self.runtime._require_active_project()
    if (problem := box_error(center, size, spacing)) is not None:
        raise ValueError(problem)
    engine_name = str(engine or "vina")
    site = self.runtime.binding_sites.save_site(
        molecule_id=int(receptor_id),
        name=str(name or "Manual Site"),
        source=str(source or "manual"),
        source_ref=str(source_ref or ""),
        center=tuple(float(value) for value in center),
        size=tuple(float(value) for value in size),
        binding_site_id=None,
        set_active=True,
        extra_data={
            **dict(metadata or {}),
            "engine": engine_name,
            "spacing": float(spacing),
        },
    )
    return {
        "receptor_id": int(receptor_id),
        "engine": engine_name,
        "binding_site_id": int(site.id or 0) or None,
        "center": [float(site.center_x or 0.0), float(site.center_y or 0.0), float(site.center_z or 0.0)],
        "size": [float(site.size_x or 0.0), float(site.size_y or 0.0), float(site.size_z or 0.0)],
        "spacing": float((site.extra_data or {}).get("spacing") or spacing),
    }

method_misfit_receptor_ids

method_misfit_receptor_ids(*, method: str) -> list[int]

Receptors whose active box does not fit the docking method (methods.py). Receptors without a box are not judged: the user still has to define one. The source structure is read: preparation keeps its metals.

Source code in src/amdockvs/docking/api.py
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
def method_misfit_receptor_ids(self, *, method: str) -> list[int]:
    """Receptors whose active box does not fit the docking `method` (methods.py).
    Receptors without a box are not judged: the user still has to define one. The source
    structure is read: preparation keeps its metals."""
    from amdockvs.docking.methods import atoms_in_box, get_method

    zinc_site = get_method(method).zinc_site
    project_db = self._project_db()
    with project_db.get_session() as session:
        rows = session.exec(
            select(MoleculeRecord, BindingSite)
            .join(BindingSite, (BindingSite.molecule_id == MoleculeRecord.id) & (BindingSite.is_active == True))  # noqa: E712
            .where(MoleculeRecord.is_receptor == True)  # noqa: E712 - SQL expression
        ).all()
    misfits: list[int] = []
    for receptor, site in rows:
        box = site_payload(site)
        if box is None:
            continue
        atoms = self._receptor_zinc_atoms(project_db, receptor)
        if atoms is not None and atoms_in_box(atoms, box["center"], box["size"]) != zinc_site:
            misfits.append(int(receptor.id))
    return misfits

list_box_residues

list_box_residues(*, receptor_id: int, engine: str = 'vina') -> list[dict[str, Any]]

Residues with at least one atom inside the receptor's active binding-site box.

Candidate set for flexible-residue selection — short because the box filters it. Returns [] when there's no active grid or the structure file is unavailable.

Source code in src/amdockvs/docking/api.py
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
def list_box_residues(self, *, receptor_id: int, engine: str = "vina") -> list[dict[str, Any]]:
    """Residues with at least one atom inside the receptor's active binding-site box.

    Candidate set for flexible-residue selection — short because the box filters it.
    Returns [] when there's no active grid or the structure file is unavailable.
    """
    grid = self.get_grid(receptor_id=int(receptor_id), engine=engine)
    if grid is None:
        return []
    center = tuple(float(v) for v in grid.get("center") or [])
    size = tuple(float(v) for v in grid.get("size") or [])
    if len(center) != 3 or len(size) != 3:
        return []
    with self.runtime.workspace.project_db.get_session() as session:
        receptor = session.get(MoleculeRecord, int(receptor_id))
    if receptor is None:
        return []
    try:
        with self._receptor_as_pdb(receptor) as readable_receptor:
            if readable_receptor is None:
                return []
            residues = residues_in_box(
                readable_receptor.read_text(encoding="utf-8", errors="ignore"), center, size
            )
    except (OSError, ValueError):
        return []
    return [
        {"key": r.key, "label": r.label, "chain": r.chain, "resname": r.resname, "resnum": r.resnum}
        for r in residues
    ]

check_receptors

check_receptors(*, program: str = key, receptor_set: MoleculeSetRef | MoleculeScope | int | None = None) -> dict[str, Any]

Receptor-only half of check_required: preparation + grid status, no ligand scan.

check_required materializes the full ligand set to report missing ligands; that's the expensive part. The Receptors step only shows receptor prep/grid status, so this skips ligands entirely (receptor sets are small).

Source code in src/amdockvs/docking/api.py
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
def check_receptors(
        self,
        *,
        program: str = VINA_PROGRAM.key,
        receptor_set: MoleculeSetRef | MoleculeScope | int | None = None,
) -> dict[str, Any]:
    """Receptor-only half of check_required: preparation + grid status, no ligand scan.

    check_required materializes the full ligand set to report missing ligands; that's
    the expensive part. The Receptors step only shows receptor prep/grid status, so this
    skips ligands entirely (receptor sets are small).
    """
    self.runtime._require_active_project()
    program_spec = self.get_program_spec(program)
    receptor_set_ref = (
        None
        if receptor_set is None or is_molecule_scope(receptor_set)
        else ensure_molecule_set_ref(self.runtime, receptor_set, name="docking_check_receptor_input")
    )
    receptor_scope = scope_payload(receptor_set) if is_molecule_scope(receptor_set) else {}
    receptor_filters = self._program_scope_filters(receptor_scope, role="receptor", program=program_spec)
    receptor_rows = list_entity_rows(
        self.runtime.workspace.project_db,
        entity_kind="receptor",
        engine=program_spec.preparation_engine,
        set_id=None if receptor_set_ref is None else int(receptor_set_ref.id),
        filters=receptor_filters,
        fields=("id", "prepared_engine", "grid_engine"),
        order=("id",),
    )
    receptor_ids = [int(row.get("id") or 0) for row in receptor_rows if int(row.get("id") or 0) > 0]
    ready_prepared = {
        int(row.get("id") or 0)
        for row in receptor_rows
        if not program_spec.requires_receptor_preparation or bool(row.get("prepared_engine"))
    }
    ready_grid = {
        int(row.get("id") or 0)
        for row in receptor_rows
        if not program_spec.requires_binding_site or bool(row.get("grid_engine"))
    }
    return {
        "receptor_ids": receptor_ids,
        "missing": {
            "receptors_prepared": [rid for rid in receptor_ids if rid not in ready_prepared],
            "receptor_binding_sites": [rid for rid in receptor_ids if rid not in ready_grid],
        },
        "counts": {
            "receptors_total": len(receptor_rows),
            "receptors_ready": len(ready_prepared),
            "receptor_grids_ready": len(ready_grid),
        },
    }

run

run(*, program: str = key, ligands: MoleculeSetRef | MoleculeScope | Selection[MoleculeRecord] | int | None = None, receptors: MoleculeSetRef | MoleculeScope | Selection[MoleculeRecord] | int | None = None, ligand_set: MoleculeSetRef | MoleculeScope | int | None = None, receptor_set: MoleculeSetRef | MoleculeScope | int | None = None, output_dir: PathLike | None = None, batch_size: int | None = None, exhaustiveness: int = 8, num_modes: int = 9, box_center: tuple[float, float, float] | None = None, box_size: tuple[float, float, float] | None = None, scoring_function: str = 'vina', vina_command: str = DEFAULT_VINA_COMMAND, vina_cpu: int = 1, seed: int = 0, spacing: float = 0.375, energy_range: float = 3.0, min_rmsd: float = 1.0, run_id: str | None = None, protocol_metadata: dict | None = None, engine_config: dict[str, Any] | None = None, executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR, depends_on: list[str] | None = None, check_required: bool = True, skip_existing: bool = True, compute_interactions: bool = False, hit_threshold: float | None = None, hit_cap: int = 0, payload: str = PAYLOAD_LIGHT, selected_from_receptor_id: int | None = None, selected_top_n: int | None = None, selected_max_score: float | None = None, replace_existing: bool = False) -> str

Run docking over the active library, selecting its row or shard adapter.

hit_threshold/hit_cap are optional for materialized rows and mandatory for a sharded library, where returning every scored molecule would defeat the storage model. compute_interactions finds each pose's interactions in the chunk that docked it. An off-target stage sets selected_from_receptor_id/selected_top_n: the other receptors dock only that receptor's Top-N ligands, read when the job starts — so it depends_on the target's job. Over rows, selected_max_score keeps only those at or below it (a sharded library uses hit_threshold for that).

Source code in src/amdockvs/docking/api.py
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
def run(
        self,
        *,
        program: str = VINA_PROGRAM.key,
        ligands: MoleculeSetRef | MoleculeScope | Selection[MoleculeRecord] | int | None = None,
        receptors: MoleculeSetRef | MoleculeScope | Selection[MoleculeRecord] | int | None = None,
        ligand_set: MoleculeSetRef | MoleculeScope | int | None = None,
        receptor_set: MoleculeSetRef | MoleculeScope | int | None = None,
        output_dir: PathLike | None = None,
        batch_size: int | None = None,
        exhaustiveness: int = 8,
        num_modes: int = 9,
        box_center: tuple[float, float, float] | None = None,
        box_size: tuple[float, float, float] | None = None,
        scoring_function: str = "vina",
        vina_command: str = DEFAULT_VINA_COMMAND,
        vina_cpu: int = 1,
        seed: int = 0,
        spacing: float = 0.375,
        energy_range: float = 3.0,
        min_rmsd: float = 1.0,
        run_id: str | None = None,
        protocol_metadata: dict | None = None,
        engine_config: dict[str, Any] | None = None,
        executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR,
        depends_on: list[str] | None = None,
        check_required: bool = True,
        skip_existing: bool = True,
        compute_interactions: bool = False,
        hit_threshold: float | None = None,
        hit_cap: int = 0,
        payload: str = PAYLOAD_LIGHT,
        selected_from_receptor_id: int | None = None,
        selected_top_n: int | None = None,
        selected_max_score: float | None = None,
        replace_existing: bool = False,
) -> str:
    """Run docking over the active library, selecting its row or shard adapter.

    ``hit_threshold``/``hit_cap`` are optional for materialized rows and mandatory for a
    sharded library, where returning every scored molecule would defeat the storage model.
    ``compute_interactions`` finds each pose's interactions in the chunk that docked it.
    An off-target stage sets ``selected_from_receptor_id``/``selected_top_n``: the other
    receptors dock only that receptor's Top-N ligands, read when the job starts — so it
    `depends_on` the target's job. Over rows, ``selected_max_score`` keeps only those at
    or below it (a sharded library uses ``hit_threshold`` for that).
    """
    if selected_top_n is not None and selected_from_receptor_id is None:
        raise ValueError("selected_top_n requires selected_from_receptor_id.")
    if ligands is not None:
        if ligand_set is not None:
            raise ValueError("Pass either ligands or ligand_set, not both.")
        ligand_set = ligands
    if receptors is not None:
        if receptor_set is not None:
            raise ValueError("Pass either receptors or receptor_set, not both.")
        receptor_set = receptors
    self.runtime._require_active_project()
    knobs = dict(
        exhaustiveness=exhaustiveness,
        num_modes=num_modes,
        scoring_function=scoring_function,
        vina_command=vina_command,
        vina_cpu=vina_cpu,
        seed=seed,
        spacing=spacing,
        energy_range=energy_range,
        min_rmsd=min_rmsd,
    )
    if ligand_set is None and has_shards(self.runtime.workspace.project_db):
        if hit_threshold is None or int(hit_cap) <= 0:
            raise ValueError(
                "docking.run over a sharded library requires hit_threshold and hit_cap."
            )
        if compute_interactions:
            raise ValueError(
                "compute_interactions is not available during sharded docking; compute "
                "interactions after hits have been materialized."
            )
        return self.run_shards(
            program=program,
            receptor_set=receptor_set,
            hit_threshold=float(hit_threshold),
            hit_cap=int(hit_cap),
            output_dir=output_dir,
            box_center=box_center,
            box_size=box_size,
            **knobs,
            run_id=run_id,
            protocol_metadata=protocol_metadata,
            engine_config=engine_config,
            executor_name=executor_name,
            depends_on=depends_on,
            skip_existing=skip_existing,
            payload=payload,
            check_required=check_required,
            selected_from_receptor_id=selected_from_receptor_id,
            selected_top_n=selected_top_n,
            replace_existing=replace_existing,
        )
    if selected_from_receptor_id is not None and not selected_top_n:
        raise ValueError("An off-target stage over ligand rows requires selected_top_n.")
    if hit_cap and hit_threshold is None:
        raise ValueError(
            "docking.run needs hit_threshold when hit_cap is set: the threshold is the "
            "scientific criterion, the cap is only what makes the run end."
        )
    program_spec = self.get_program_spec(program)
    resolved_engine_config = _validated_engine_config(program_spec, engine_config, **knobs)
    protocol_metadata = self.check_protocol(
        program=program_spec.key, engine_config=resolved_engine_config,
        protocol_metadata=protocol_metadata, replace_existing=replace_existing,
    )
    reset_results = replace_existing and check_protocol_conflict(
        self.runtime.workspace.project_db, program=program_spec, protocol=protocol_metadata, replace_existing=True,
    )
    if reset_results and selected_from_receptor_id is not None:
        raise ValueError("Changing docking configuration requires rerunning the reference stage before off-target docking.")
    resolved_batch_size = self.pairs_per_task(program_spec, batch_size)
    ligand_set_ref = self._set_ref(ligand_set, name="docking_ligand_input")
    receptor_set_ref = self._set_ref(receptor_set, name="docking_receptor_input")
    ligand_scope = scope_payload(ligand_set) if is_molecule_scope(ligand_set) else {}
    receptor_scope = scope_payload(receptor_set) if is_molecule_scope(receptor_set) else {}
    ligand_filters = self._program_scope_filters(ligand_scope, role="ligand", program=program_spec)
    receptor_filters = self._program_scope_filters(receptor_scope, role="receptor", program=program_spec)
    if box_center is None or box_size is None:
        resolved_grid = self._grid_from_receptor_source(
            receptor_set if is_molecule_scope(receptor_set) else receptor_set_ref,
            engine=program_spec.preparation_engine,
        )
        if resolved_grid is not None:
            box_center, box_size, knobs["spacing"] = resolved_grid
    if (box_center is None) ^ (box_size is None):
        raise ValueError("docking.run requires both box_center and box_size when either one is provided.")
    if box_center is not None and (problem := box_error(box_center, box_size)) is not None:
        raise ValueError(problem)
    # Always resolve counts: they gate readiness (when requested) AND give the true
    # chunk total so progress is computed against the real pair count instead of
    # completed/emitted-so-far (a lazy generator otherwise leaves total_chunks unknown,
    # making progress hover near 50-60% regardless of actual completion).
    requirement_check = self.check_required(
        program=program_spec.key,
        ligand_set=ligand_set if is_molecule_scope(ligand_set) else ligand_set_ref,
        receptor_set=receptor_set if is_molecule_scope(receptor_set) else receptor_set_ref,
    )
    if check_required and not bool(requirement_check.get("ready")):
        raise RuntimeError(_requirements_message(program_spec.key, requirement_check))
    run_counts = dict(requirement_check.get("counts") or {})
    # The docking feed pairs every prepared ligand with every prepared receptor
    # (receptors without a grid still emit a failed-pair chunk), batched by batch_size.
    total_pairs = int(run_counts.get("ligands_ready") or 0) * int(run_counts.get("receptors_ready") or 0)
    if check_required and total_pairs <= 0:
        # Fail early and clearly instead of submitting a job whose feed yields no pairs
        # (which would otherwise complete silently with zero results).
        raise RuntimeError(
            f"docking.run has no valid ligand-receptor pairs to dock for docking.{program_spec.key}: "
            f"counts={run_counts}. Import and prepare at least one ligand and one receptor first."
        )
    # The feed applies skip_existing after resolving the scoped cross-product. Its declared
    # total must use that same filtered count; over-declaring makes Molsuite wait forever for
    # chunks that the feed intentionally never emits.
    pending_pairs = count_pending_docking_pairs(
        project_db=self.runtime.workspace.project_db,
        engine=program_spec.docking_engine,
        preparation_engine=program_spec.preparation_engine,
        ligand_set_id=None if ligand_set_ref is None else int(ligand_set_ref.id),
        receptor_set_id=None if receptor_set_ref is None else int(receptor_set_ref.id),
        ligand_filters=ligand_filters,
        receptor_filters=receptor_filters,
        protocol_metadata=protocol_metadata,
        skip_existing=False if reset_results else skip_existing,
        requires_ligand_preparation=program_spec.requires_ligand_preparation,
        requires_receptor_preparation=program_spec.requires_receptor_preparation,
        requires_binding_site=program_spec.requires_binding_site,
        box_center=box_center,
        box_size=box_size,
        spacing=_engine_fields(resolved_engine_config, knobs)["spacing"],
    )
    # The Top-N does not exist yet when an off-target stage is submitted: declare nothing
    # (a floor of 0) rather than a count that could over-declare and never complete.
    total_chunks = (
        -(-pending_pairs // resolved_batch_size)
        if pending_pairs > 0 and selected_from_receptor_id is None else 0
    )
    params = DockingJobParams(
        output_dir=self._output_dir(output_dir),
        batch_size=resolved_batch_size,
        row_batch_size=batch_size_for("ligand", self.runtime),
        ligand_set_id=None if ligand_set_ref is None else int(ligand_set_ref.id),
        receptor_set_id=None if receptor_set_ref is None else int(receptor_set_ref.id),
        ligand_filters=ligand_filters,
        receptor_filters=receptor_filters,
        engine=program_spec.docking_engine,
        preparation_engine=program_spec.preparation_engine,
        requires_ligand_preparation=program_spec.requires_ligand_preparation,
        requires_receptor_preparation=program_spec.requires_receptor_preparation,
        requires_binding_site=program_spec.requires_binding_site,
        box_center=box_center,
        box_size=box_size,
        **_engine_fields(resolved_engine_config, knobs),
        run_id=str(run_id or uuid4().hex),
        protocol_metadata=dict(protocol_metadata or {}),
        engine_config=resolved_engine_config,
        skip_existing=skip_existing,
        hit_threshold=hit_threshold,
        hit_cap=max(0, int(hit_cap)),
        interactions=bool(compute_interactions),
        selected_from_receptor_id=selected_from_receptor_id,
        selected_top_n=selected_top_n,
        selected_max_score=selected_max_score,
    )
    cpu = program_spec.resource_requirements(resolved_engine_config)["cpu_required"]
    if self.runtime.is_queue(executor_name):
        return self._run_rows_on_queue(params, executor_name=executor_name, cpu=cpu, depends_on=depends_on,
                                       reset_results=reset_results, program_spec=program_spec)
    if reset_results:
        clear_previous_docking(self.runtime.workspace.project_db, program=program_spec)
    job_id = self.runtime.submit_job(
        docking_job,
        queue_behind="docking",
        params=params.model_dump(mode="python"),
        executor_name=executor_name,
        depends_on=depends_on,
        # Each docking chunk runs one engine process that uses `vina_cpu` threads
        # internally, so reserve that many CPU tokens from the pool to avoid
        # oversubscription (pool limits concurrency to floor(cpus / vina_cpu)).
        cpu_required=cpu,
        # Declare the real chunk total so progress = processed/total (not processed/emitted).
        total_chunks=total_chunks,
        autobatch=self.autobatch(program_spec, batch_size),
    )
    if total_chunks:
        single = int(run_counts.get("receptors_ready") or 0) == 1
        self.runtime.track_chunk_items(job_id, pending_pairs, resolved_batch_size,
                                       unit="ligands" if single else "pairs")
    return job_id

move_to_queue

move_to_queue(job_id: str, executor_name: str) -> str

Continue a docking run over rows on a cluster's queue: it is stopped here (waited for, so not from a thread that cannot wait) and what it has not docked goes there as a run of its own (_run_rows_on_queue), with its run id. The id of that new job.

Source code in src/amdockvs/docking/api.py
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
def move_to_queue(self, job_id: str, executor_name: str) -> str:
    """Continue a docking run over rows on a cluster's queue: it is stopped here (waited for,
    so not from a thread that cannot wait) and what it has not docked goes there as a run of
    its own (`_run_rows_on_queue`), with its run id. The id of that new job."""
    params = DockingJobParams(**self.runtime.workspace.origin(str(job_id))["params"])
    self._check_queue(params)  # before it is stopped here
    engine_id = self.runtime._engine_ids().get(str(job_id))
    if engine_id is not None:
        self.runtime.workspace.engine.cancel(engine_id)
        self.runtime.workspace.engine.wait(engine_id)
    program_spec = self.get_program_spec(params.protocol_metadata.program or params.engine)
    cpu = program_spec.resource_requirements(params.engine_config)["cpu_required"]
    return self._run_rows_on_queue(params.model_copy(update={"skip_existing": True}), executor_name=executor_name,
                                   cpu=cpu, depends_on=None, reset_results=False, program_spec=program_spec)

has_results

has_results() -> bool

Whether the project has docking results or completed screening fragments.

Source code in src/amdockvs/docking/api.py
1536
1537
1538
def has_results(self) -> bool:
    """Whether the project has docking results or completed screening fragments."""
    return results_repo.has_docking_results(self._project_db())

ligand_summaries

ligand_summaries(*, limit: int = 200, offset: int = 0, receptor_id: int | None = None, only_completed: bool = False, score_lte: float | None = None, metric_key: str | None = None, metric_lte: float | None = None, metric_gte: float | None = None, metric_filters: list[tuple[str, str, float]] | None = None, protocol_hash: str | None = None, exclude_run_kind: str | None = 'redocking')

(best pose, pose count) per ligand, one page at a time.

Source code in src/amdockvs/docking/api.py
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
def ligand_summaries(
        self,
        *,
        limit: int = 200,
        offset: int = 0,
        receptor_id: int | None = None,
        only_completed: bool = False,
        score_lte: float | None = None,
        metric_key: str | None = None,
        metric_lte: float | None = None,
        metric_gte: float | None = None,
        metric_filters: list[tuple[str, str, float]] | None = None,
        protocol_hash: str | None = None,
        exclude_run_kind: str | None = "redocking",
):
    """(best pose, pose count) per ligand, one page at a time."""
    return results_repo.list_ligand_result_summaries(
        self._project_db(),
        limit=limit,
        offset=offset,
        receptor_id=receptor_id,
        only_completed=only_completed,
        score_lte=score_lte,
        metric_key=metric_key,
        metric_lte=metric_lte,
        metric_gte=metric_gte,
        metric_filters=metric_filters,
        protocol_hash=protocol_hash,
        exclude_run_kind=exclude_run_kind,
    )

compute_diagrams

compute_diagrams(*, result_ids: list[int] | None = None, run_id: str = '', receptor_id: int | None = None, score_lte: float | None = None, pose_rank: int | None = 1, fmt: str = 'png', chunk_size: int = 64, replace_existing: bool = False, executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR, depends_on: list[str] | None = None) -> str

Render 2D interaction diagrams for docking poses as a standalone job.

Files land next to each pose (see diagram.diagram_path_for); nothing is written to the DB, so re-run with replace_existing=True to refresh.

Source code in src/amdockvs/docking/api.py
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
def compute_diagrams(
        self,
        *,
        result_ids: list[int] | None = None,
        run_id: str = "",
        receptor_id: int | None = None,
        score_lte: float | None = None,
        pose_rank: int | None = 1,
        fmt: str = "png",
        chunk_size: int = 64,
        replace_existing: bool = False,
        executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR,
        depends_on: list[str] | None = None,
) -> str:
    """Render 2D interaction diagrams for docking poses as a standalone job.

    Files land next to each pose (see ``diagram.diagram_path_for``); nothing
    is written to the DB, so re-run with ``replace_existing=True`` to refresh.
    """
    self.runtime._require_active_project()
    params = DiagramJobParams(
        result_ids=[int(value) for value in (result_ids or []) if int(value) > 0],
        run_id=str(run_id or ""),
        receptor_id=receptor_id,
        score_lte=score_lte,
        pose_rank=pose_rank,
        fmt=str(fmt or "png"),
        chunk_size=max(1, int(chunk_size)),
        replace_existing=bool(replace_existing),
    )
    return self.runtime.submit_job(
        diagram_job,
        params=params.model_dump(mode="python"),
        executor_name=executor_name,
        depends_on=depends_on,
    )

diagram_path

diagram_path(*, pose_path: str, pose_rank: int = 1, fmt: str = 'png') -> str

Convention path for a pose's diagram (may not exist yet).

Source code in src/amdockvs/docking/api.py
1692
1693
1694
1695
1696
1697
def diagram_path(self, *, pose_path: str, pose_rank: int = 1, fmt: str = "png") -> str:
    """Convention path for a pose's diagram (may not exist yet)."""
    from amdockvs.docking.results.diagram import diagram_path_for

    suffix = ".svg" if str(fmt).lower() == "svg" else ".png"
    return str(diagram_path_for(pose_path, pose_rank, suffix=suffix))

count_docked_pairs

count_docked_pairs(*, engine: str = '', receptor_ids: list[int] | None = None, protocol_hash: str | None = None, run_kind: str | None = 'screening', program: str | None = None) -> int

program counts only the pairs docked against what its run would dock now: each receptor's current preparation and stored grid (skip_existing docks the others again).

The spacing is the stored grid's, which is what the run docks with as well: a defined site always carries one, so the fallback here is only reached where there is no grid — and then there is nothing docked to count, every program requiring a site.

Source code in src/amdockvs/docking/api.py
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
def count_docked_pairs(
        self,
        *,
        engine: str = "",
        receptor_ids: list[int] | None = None,
        protocol_hash: str | None = None,
        run_kind: str | None = "screening",
        program: str | None = None,
) -> int:
    """`program` counts only the pairs docked against what its run would dock now: each
    receptor's current preparation and stored grid (skip_existing docks the others again).

    The spacing is the stored grid's, which is what the run docks with as well: a defined
    site always carries one, so the fallback here is only reached where there is no grid —
    and then there is nothing docked to count, every program requiring a site."""
    input_keys = None
    if program and receptor_ids is not None:
        spec = self.get_program_spec(program)
        rows = get_molecule_rows_by_ids(self._project_db(), list(receptor_ids), engine=spec.preparation_engine)
        input_keys = screening_input_keys(rows.values(), box_center=None, box_size=None, spacing=0.375,
                                          preparation_engine=spec.preparation_engine,
                                          requires_binding_site=spec.requires_binding_site)
    return results_repo.count_docked_pairs(
        self._project_db(),
        engine=engine,
        receptor_ids=receptor_ids,
        protocol_hash=protocol_hash,
        run_kind=run_kind,
        input_keys=input_keys,
    )

Diversity

DiversityAPI dataclass

DiversityAPI(runtime: Any)

Methods:

Name Description
cluster_job

Submit the clustering job over the DB; results land in clustering_results. Returns

load_universe

Load a scope's fingerprint matrix + 2-D projection for the interactive view. Samples a

cluster_loaded

Cluster an already-loaded UniverseMatrix — the cheap step that re-runs on every knob

analyze

Convenience: load_universe then cluster_loaded in one call (scripting/preview).

scope_count

How many molecules a scope holds — the cheap count used to route serial vs. parallel

run_selection

Cluster the ENTIRE scope (no sampling) and pick representatives — the real 'run the

register_run_from_sidecar

Register a finished parallel run as a saved result WITHOUT recomputing anything: the job's

list_runs

Persisted clustering runs, newest first: run id, method, cluster/centroid counts.

pick_representatives

Choose again what represents each cluster of a finished run. Nothing is clustered

members_clause

Opaque SmartTable adapter: the molecules of one cluster, or the run's representatives

exclude_non_representatives

Mark every non-representative of a run as excluded (the flag Filter uses; reversible).

save_selection_as_set

Persist the chosen representatives as a molecule set (an enrichment set) so the rest of

molblock_for

A 2-D-drawable molblock for one molecule (its stored structure), or None if there's

save_clustering_result

Persist an applied clustering as a durable run: the graph points (x, y, molecule_id,

list_clustering_results

Saved runs, newest first — for the results table.

load_clustering_result

Everything needed to redraw a saved run (graph points + cluster stats + evr) — read the

cluster_job

cluster_job(*, method: str = 'bitbirch', threshold: float = 0.65, per_cluster: int = 1, molecule_set: MoleculeSetRef | int | None = None, molecule_filters: dict[str, Any] | None = None, fp_radius: int = 2, fp_nbits: int = 2048, with_activity: str = '', cluster_run_id: str = '', num_cpus: int | None = None, executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR, depends_on: list[str] | None = None, shards: bool = False) -> str

Submit the clustering job over the DB; results land in clustering_results. Returns the job id. The run is tagged with cluster_run_id (auto if blank) — read it back with list_runs / get_run or persist its centroids with save_centroids_as_set. with_activity (an activity endpoint) narrows the scope to the ligands measured for it.

Each cluster starts with its per_cluster centroid-nearest members as representatives; pick_representatives chooses again, by any mode, without clustering again.

num_cpus sets the parallelism: >1 runs bblean multiround with that many processes and the job requests exactly that many CPUs (cpu_required) so mf schedules it correctly. When None it is derived from the scope size via plan_cpus.

shards clusters the library's shards instead (the scope arguments do not apply): a fingerprint job packs them shard by shard, the clustering waits for it, and only the representatives become molecule rows; every member stays in the run's sidecar by io.shards.shard_key. Both jobs run at SHARDS_PRIORITY.

Source code in src/amdockvs/diversity/api.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def cluster_job(
    self,
    *,
    method: str = "bitbirch",
    threshold: float = 0.65,
    per_cluster: int = 1,
    molecule_set: MoleculeSetRef | int | None = None,
    molecule_filters: dict[str, Any] | None = None,
    fp_radius: int = 2,
    fp_nbits: int = 2048,
    with_activity: str = "",
    cluster_run_id: str = "",
    num_cpus: int | None = None,
    executor_name: str = DEFAULT_LOCAL_CPU_EXECUTOR,
    depends_on: list[str] | None = None,
    shards: bool = False,
) -> str:
    """Submit the clustering job over the DB; results land in ``clustering_results``. Returns
    the job id. The run is tagged with ``cluster_run_id`` (auto if blank) — read it back with
    ``list_runs`` / ``get_run`` or persist its centroids with ``save_centroids_as_set``.
    ``with_activity`` (an activity endpoint) narrows the scope to the ligands measured for it.

    Each cluster starts with its ``per_cluster`` centroid-nearest members as representatives;
    ``pick_representatives`` chooses again, by any mode, without clustering again.

    ``num_cpus`` sets the parallelism: >1 runs bblean multiround with that many processes and the
    job **requests exactly that many CPUs** (``cpu_required``) so mf schedules it correctly. When
    None it is derived from the scope size via ``plan_cpus``.

    ``shards`` clusters the library's shards instead (the scope arguments do not apply): a
    fingerprint job packs them shard by shard, the clustering waits for it, and only the
    representatives become molecule rows; every member stays in the run's sidecar by
    ``io.shards.shard_key``. Both jobs run at ``SHARDS_PRIORITY``."""
    self.runtime._require_active_project()
    if cluster_run_id and self._run_id_in_use(cluster_run_id):
        # The worker writes the run's graph sidecar before its rows reach the UNIQUE
        # constraint: a second job under this id would fail AND overwrite the first's graph.
        raise ValueError(
            f"Clustering run '{cluster_run_id}' already exists; choose another run id "
            "(or leave it blank for a new one)."
        )
    if num_cpus is None and shards:
        num_cpus = plan_cpus(ShardStore(self.runtime.workspace.project_db).record_count())
    if num_cpus is None:
        num_cpus = plan_cpus(
            self.scope_count(
                molecule_set=molecule_set, molecule_filters=molecule_filters,
                fp_radius=fp_radius, fp_nbits=fp_nbits, with_activity=with_activity,
            )
        )
    num_cpus = max(1, int(num_cpus))
    params = SelectionClusterJobParams(
        batch_size=app_config(self.runtime).diversity.rows_per_task,
        method=method,
        threshold=threshold,
        per_cluster=per_cluster,
        molecule_set_id=None if molecule_set is None else int(getattr(molecule_set, "id", molecule_set)),
        molecule_filters=dict(molecule_filters or {}),
        fp_radius=fp_radius,
        fp_nbits=fp_nbits,
        with_activity=with_activity,
        cluster_run_id=cluster_run_id or uuid.uuid4().hex,
        num_processes=num_cpus,
        shards=shards,
    )
    priority = {}
    if shards:
        priority = {"priority": SHARDS_PRIORITY}
        depends_on = [self.runtime.submit_job(
            shard_fingerprints_job, params=params.model_dump(mode="python"), executor_name=executor_name,
            depends_on=depends_on, **priority,
        )]
    return self.runtime.submit_job(
        cluster_molecules_job,
        params=params.model_dump(mode="python"),
        executor_name=executor_name,
        cpu_required=num_cpus,
        depends_on=depends_on,
        **priority,
    )

load_universe

load_universe(*, molecule_set: MoleculeSetRef | int | None = None, molecule_filters: dict[str, Any] | None = None, fp_radius: int = 2, fp_nbits: int = 2048, with_activity: str = '', sample_limit: int = DEFAULT_SAMPLE_LIMIT, seed: int = 0, basis: Any = None, exclude_ids: Any = None) -> UniverseMatrix

Load a scope's fingerprint matrix + 2-D projection for the interactive view. Samples a random sample_limit subset (seeded by seed so each preview draws a fresh subset), skipping exclude_ids (molecules already previewed) so repeated previews cover more of the space. Projects onto basis when given (a prior preview's fitted PCA axes) so runs overlay in one comparable space; otherwise fits a new basis and returns it. Heavy (DB read + PCA); call off the GUI thread. with_activity restricts the scope to ligands measured for that endpoint, as in cluster_job. Cheap re-clustering then uses cluster_loaded.

Source code in src/amdockvs/diversity/api.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def load_universe(
    self,
    *,
    molecule_set: MoleculeSetRef | int | None = None,
    molecule_filters: dict[str, Any] | None = None,
    fp_radius: int = 2,
    fp_nbits: int = 2048,
    with_activity: str = "",
    sample_limit: int = DEFAULT_SAMPLE_LIMIT,
    seed: int = 0,
    basis: Any = None,
    exclude_ids: Any = None,
) -> UniverseMatrix:
    """Load a scope's fingerprint matrix + 2-D projection for the interactive view. Samples a
    random ``sample_limit`` subset (seeded by ``seed`` so each preview draws a *fresh* subset),
    skipping ``exclude_ids`` (molecules already previewed) so repeated previews cover more of
    the space. Projects onto ``basis`` when given (a prior preview's fitted PCA axes) so runs
    overlay in one comparable space; otherwise fits a new basis and returns it. Heavy (DB read +
    PCA); call off the GUI thread. ``with_activity`` restricts the scope to ligands measured
    for that endpoint, as in ``cluster_job``. Cheap re-clustering then uses ``cluster_loaded``."""
    import random

    from amdockvs.diversity.clustering import fit_project_2d, fp_matrix_from_bitstrings, project_2d_onto

    self.runtime._require_active_project()
    params = SelectionClusterJobParams(
        batch_size=app_config(self.runtime).diversity.rows_per_task,
        molecule_set_id=None if molecule_set is None else int(getattr(molecule_set, "id", molecule_set)),
        molecule_filters=dict(molecule_filters or {}),
        fp_radius=fp_radius,
        fp_nbits=fp_nbits,
        with_activity=with_activity,
    )
    project_db = self.runtime.workspace.project_db
    skip = {int(i) for i in (exclude_ids or ())}
    rows, total, eligible = _reservoir_sample(
        scope_molecule_rows(project_db, params),
        limit=int(sample_limit),
        seed=int(seed),
        skip=skip,
    )
    sampled = eligible > int(sample_limit)
    stored = stored_fingerprints_for_ids(
        project_db, [int(r["id"]) for r in rows], radius=fp_radius, nbits=fp_nbits
    )
    ordered_ids: list[int] = []
    bitstrings: list[bytes] = []
    for row in rows:
        mol_id = int(row["id"])
        fp = stored.get(mol_id) or _fingerprint_from_structure(project_db, row, radius=fp_radius, nbits=fp_nbits)
        if fp is None:
            continue
        ordered_ids.append(mol_id)
        bitstrings.append(fp)
    x_matrix = fp_matrix_from_bitstrings(bitstrings)
    if basis is None:
        projection, evr, basis = fit_project_2d(x_matrix)
    else:
        projection, evr = project_2d_onto(x_matrix, basis), list(basis.get("evr") or [0.0, 0.0])
    return UniverseMatrix(
        molecule_ids=ordered_ids,
        x_matrix=x_matrix,
        projection=[[float(x), float(y)] for x, y in projection],
        projection_variance=list(evr),
        total_in_scope=total,
        sampled=sampled,
        basis=basis,
    )

cluster_loaded staticmethod

cluster_loaded(universe: UniverseMatrix, *, method: str = 'bitbirch', per_cluster: int = 1, **method_params: Any) -> AnalysisResult

Cluster an already-loaded UniverseMatrix — the cheap step that re-runs on every knob change without touching the DB. method_params (threshold, batch_size, ...) go straight to the registered method, so each method's own knobs pass through untouched.

Source code in src/amdockvs/diversity/api.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
@staticmethod
def cluster_loaded(
    universe: UniverseMatrix,
    *,
    method: str = "bitbirch",
    per_cluster: int = 1,
    **method_params: Any,
) -> AnalysisResult:
    """Cluster an already-loaded ``UniverseMatrix`` — the cheap step that re-runs on every knob
    change without touching the DB. ``method_params`` (threshold, batch_size, ...) go straight to
    the registered method, so each method's own knobs pass through untouched."""
    threshold = float(method_params.get("threshold", 0.65))
    if not universe.molecule_ids:
        return AnalysisResult(
            [], [], [], {"n_clusters": 0, "n_molecules": 0, "clusters": []}, [], [0.0, 0.0],
            method, threshold, universe.total_in_scope, universe.sampled,
        )
    result = cluster_and_select(
        universe.x_matrix, method=method, per_cluster=per_cluster, with_projection=False, **method_params
    )
    rep_ids = [universe.molecule_ids[i] for i in result.representative_indices]
    return AnalysisResult(
        molecule_ids=universe.molecule_ids,
        labels=[int(v) for v in result.labels],
        representative_ids=rep_ids,
        stats=result.stats,
        projection=universe.projection,
        projection_variance=universe.projection_variance,
        method=method,
        threshold=threshold,
        total_in_scope=universe.total_in_scope,
        sampled=universe.sampled,
    )

analyze

analyze(*, method: str = 'bitbirch', threshold: float = 0.65, per_cluster: int = 1, molecule_set: MoleculeSetRef | int | None = None, molecule_filters: dict[str, Any] | None = None, fp_radius: int = 2, fp_nbits: int = 2048, sample_limit: int = DEFAULT_SAMPLE_LIMIT) -> AnalysisResult

Convenience: load_universe then cluster_loaded in one call (scripting/preview).

Source code in src/amdockvs/diversity/api.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def analyze(
    self,
    *,
    method: str = "bitbirch",
    threshold: float = 0.65,
    per_cluster: int = 1,
    molecule_set: MoleculeSetRef | int | None = None,
    molecule_filters: dict[str, Any] | None = None,
    fp_radius: int = 2,
    fp_nbits: int = 2048,
    sample_limit: int = DEFAULT_SAMPLE_LIMIT,
) -> AnalysisResult:
    """Convenience: ``load_universe`` then ``cluster_loaded`` in one call (scripting/preview)."""
    universe = self.load_universe(
        molecule_set=molecule_set,
        molecule_filters=molecule_filters,
        fp_radius=fp_radius,
        fp_nbits=fp_nbits,
        sample_limit=sample_limit,
    )
    return self.cluster_loaded(universe, method=method, threshold=threshold, per_cluster=per_cluster)

scope_count

scope_count(*, molecule_set: MoleculeSetRef | int | None = None, molecule_filters: dict[str, Any] | None = None, fp_radius: int = 2, fp_nbits: int = 2048, with_activity: str = '') -> int

How many molecules a scope holds — the cheap count used to route serial vs. parallel (no fingerprint load, no clustering). Reads ids only via the MolSuite query API.

Source code in src/amdockvs/diversity/api.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
def scope_count(
    self,
    *,
    molecule_set: MoleculeSetRef | int | None = None,
    molecule_filters: dict[str, Any] | None = None,
    fp_radius: int = 2,
    fp_nbits: int = 2048,
    with_activity: str = "",
) -> int:
    """How many molecules a scope holds — the cheap count used to route serial vs. parallel
    (no fingerprint load, no clustering). Reads ids only via the MolSuite query API."""
    self.runtime._require_active_project()
    params = SelectionClusterJobParams(
        batch_size=app_config(self.runtime).diversity.rows_per_task,
        molecule_set_id=None if molecule_set is None else int(getattr(molecule_set, "id", molecule_set)),
        molecule_filters=dict(molecule_filters or {}),
        fp_radius=fp_radius,
        fp_nbits=fp_nbits,
        with_activity=with_activity,
    )
    return scope_molecule_count(self.runtime.workspace.project_db, params)

run_selection

run_selection(*, method: str = 'bitbirch', per_cluster: int = 1, molecule_set: MoleculeSetRef | int | None = None, molecule_filters: dict[str, Any] | None = None, fp_radius: int = 2, fp_nbits: int = 2048, **method_params: Any) -> dict[str, Any]

Cluster the ENTIRE scope (no sampling) and pick representatives — the real 'run the selection' behind the interactive Preview. Every molecule's fingerprint is loaded and clustered (bblean is fast); only the 2-D graph basis is fitted on a random sub-sample and every point projected onto it (cheap), so the plot scales without the full-N SVD. Returns the same mapping as cluster_loaded, over the whole scope. Heavy — call off the GUI thread. Raises if the scope exceeds INLINE_RUN_LIMIT (that needs the parallel job).

Source code in src/amdockvs/diversity/api.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
def run_selection(
    self,
    *,
    method: str = "bitbirch",
    per_cluster: int = 1,
    molecule_set: MoleculeSetRef | int | None = None,
    molecule_filters: dict[str, Any] | None = None,
    fp_radius: int = 2,
    fp_nbits: int = 2048,
    **method_params: Any,
) -> dict[str, Any]:
    """Cluster the ENTIRE scope (no sampling) and pick representatives — the real 'run the
    selection' behind the interactive Preview. Every molecule's fingerprint is loaded and
    clustered (bblean is fast); only the 2-D graph basis is fitted on a random sub-sample and
    every point projected onto it (cheap), so the plot scales without the full-N SVD. Returns the
    same mapping as ``cluster_loaded``, over the whole scope. Heavy — call off the GUI thread.
    Raises if the scope exceeds ``INLINE_RUN_LIMIT`` (that needs the parallel job)."""
    import random

    from amdockvs.diversity.clustering import (
        fit_project_2d,
        fp_matrix_from_bitstrings,
        project_2d_onto,
    )

    self.runtime._require_active_project()
    params = SelectionClusterJobParams(
        batch_size=app_config(self.runtime).diversity.rows_per_task,
        molecule_set_id=None if molecule_set is None else int(getattr(molecule_set, "id", molecule_set)),
        molecule_filters=dict(molecule_filters or {}),
        fp_radius=fp_radius,
        fp_nbits=fp_nbits,
    )
    project_db = self.runtime.workspace.project_db
    # Stop one row past the limit instead of loading the scope first: a scope too big for the
    # inline path must not be materialized just to be rejected.
    rows = list(islice(scope_molecule_rows(project_db, params), INLINE_RUN_LIMIT + 1))
    if len(rows) > INLINE_RUN_LIMIT:
        raise ValueError(
            f"More than {INLINE_RUN_LIMIT} molecules exceed the serial limit - this scope belongs "
            f"on the parallel clustering job (cluster_job), not the inline path."
        )
    total = len(rows)
    stored = stored_fingerprints_for_ids(
        project_db, [int(r["id"]) for r in rows], radius=fp_radius, nbits=fp_nbits
    )
    ordered_ids: list[int] = []
    bitstrings: list[bytes] = []
    for row in rows:
        mol_id = int(row["id"])
        fp = stored.get(mol_id) or _fingerprint_from_structure(project_db, row, radius=fp_radius, nbits=fp_nbits)
        if fp is None:
            continue
        ordered_ids.append(mol_id)
        bitstrings.append(fp)
    x_matrix = fp_matrix_from_bitstrings(bitstrings)
    universe = UniverseMatrix(
        molecule_ids=ordered_ids, x_matrix=x_matrix, projection=[],
        projection_variance=[0.0, 0.0], total_in_scope=total, sampled=False,
    )
    n = len(ordered_ids)
    if n:
        fit_idx = list(range(n))
        if n > PROJECT_FIT_SAMPLE:
            fit_idx = random.Random(0).sample(fit_idx, PROJECT_FIT_SAMPLE)
        _coords, evr, basis = fit_project_2d(x_matrix[fit_idx])
        proj = project_2d_onto(x_matrix, basis)
        universe.projection = [[float(x), float(y)] for x, y in proj]
        universe.projection_variance = list(evr)
    return self.cluster_loaded(
        universe, method=method, per_cluster=per_cluster, **method_params
    ).to_mapping()

register_run_from_sidecar

register_run_from_sidecar(cluster_run_id: str, *, method: str, threshold: float, scope_label: str, fp_radius: int = 2, fp_nbits: int = 2048) -> str

Register a finished parallel run as a saved result WITHOUT recomputing anything: the job's task already wrote the graph sidecar <root>/clustering_runs/<run_id>.parquet (PCA points + cluster/centroid flags). Read it for the counts + aggregated cluster sizes and insert the compact ClusteringRun summary pointing at it. No fingerprints, no PCA here.

Source code in src/amdockvs/diversity/api.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
def register_run_from_sidecar(
    self,
    cluster_run_id: str,
    *,
    method: str,
    threshold: float,
    scope_label: str,
    fp_radius: int = 2,
    fp_nbits: int = 2048,
) -> str:
    """Register a finished parallel run as a saved result WITHOUT recomputing anything: the job's
    task already wrote the graph sidecar ``<root>/clustering_runs/<run_id>.parquet`` (PCA points +
    cluster/centroid flags). Read it for the counts + aggregated cluster sizes and insert the
    compact ``ClusteringRun`` summary pointing at it. No fingerprints, no PCA here."""
    import pandas as pd

    self.runtime._require_active_project()
    snapshot = self._project_root() / "clustering_runs" / f"{cluster_run_id}.parquet"
    if snapshot.exists():
        frame = pd.read_parquet(snapshot)
        n_molecules = int(len(frame))
        n_clusters = int(frame["cluster_id"].nunique()) if n_molecules else 0
        n_reps = int(frame["is_centroid"].sum()) if n_molecules else 0
        cluster_stats = [
            {"cluster_id": int(cid), "size": int(size), "tightness": 0.0}
            for cid, size in frame.groupby("cluster_id").size().items()
        ]
        snapshot_path = str(snapshot)
        # Empty when the sidecar predates it: "not recorded", never a made-up 0.0%.
        evr = [float(value) for value in frame.attrs.get("evr") or []]
    else:  # sidecar missing (e.g. write failed) → counts-only summary, no graph
        n_molecules = n_clusters = n_reps = 0
        cluster_stats = []
        snapshot_path = ""
        evr = []
    row = ClusteringRun(
        run_id=cluster_run_id, method=str(method), threshold=float(threshold),
        scope_label=str(scope_label), fp_radius=int(fp_radius), fp_nbits=int(fp_nbits),
        n_molecules=n_molecules, n_clusters=n_clusters, n_reps=n_reps,
        snapshot_path=snapshot_path, evr=evr, cluster_stats=cluster_stats,
    )
    with self.runtime.workspace.project_db.get_session() as session:
        session.add(row)
        session.commit()
    return cluster_run_id

list_runs

list_runs() -> list[dict[str, Any]]

Persisted clustering runs, newest first: run id, method, cluster/centroid counts.

Source code in src/amdockvs/diversity/api.py
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
def list_runs(self) -> list[dict[str, Any]]:
    """Persisted clustering runs, newest first: run id, method, cluster/centroid counts."""
    self.runtime._require_active_project()
    with self.runtime.workspace.project_db.get_session() as session:
        rows = session.exec(select(ClusteringResult).order_by(ClusteringResult.id)).all()
    runs: dict[str, dict[str, Any]] = {}
    for row in rows:
        entry = runs.setdefault(
            row.cluster_run_id,
            {"cluster_run_id": row.cluster_run_id, "method": row.method,
             "n_molecules": 0, "n_clusters": set(), "n_centroids": 0},
        )
        entry["n_molecules"] += 1
        entry["n_clusters"].add(int(row.cluster_id))
        if row.is_centroid:
            entry["n_centroids"] += 1
    out = []
    for entry in runs.values():
        entry["n_clusters"] = len(entry["n_clusters"])
        out.append(entry)
    return out[::-1]  # runs in order of their first row: newest first

pick_representatives

pick_representatives(cluster_run_id: str, *, mode: str = 'centroid', per_cluster: int = 1, fraction: float = 0.1, rank_by: str = '') -> dict[str, int]

Choose again what represents each cluster of a finished run. Nothing is clustered again: the run already ranks every member, and this only reads that ranking (modes: see clustering.pick_representatives). rank_by (an activity endpoint) replaces similarity as what 'extremes' / 'quartiles' / 'proportional' spread over. Rewrites the run's representative flags; returns {"n_molecules", "n_clusters", "n_reps"}.

ponytail: in-process over the run's columns (~20 B/molecule) and one UPDATE per 900 picks. Make it a job when a run outgrows the tens of millions.

Source code in src/amdockvs/diversity/api.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def pick_representatives(
    self,
    cluster_run_id: str,
    *,
    mode: str = "centroid",
    per_cluster: int = 1,
    fraction: float = 0.1,
    rank_by: str = "",
) -> dict[str, int]:
    """Choose again what represents each cluster of a finished run. Nothing is clustered
    again: the run already ranks every member, and this only reads that ranking (modes:
    see ``clustering.pick_representatives``). ``rank_by`` (an activity endpoint) replaces
    similarity as what 'extremes' / 'quartiles' / 'proportional' spread over. Rewrites the
    run's representative flags; returns {"n_molecules", "n_clusters", "n_reps"}.

    ponytail: in-process over the run's columns (~20 B/molecule) and one UPDATE per 900
    picks. Make it a job when a run outgrows the tens of millions."""
    import pandas as pd

    self.runtime._require_active_project()
    run_id = str(cluster_run_id)
    sidecar = self._project_root() / "clustering_runs" / f"{run_id}.parquet"
    frame = pd.read_parquet(sidecar) if sidecar.exists() else None
    if frame is None or "similarity" not in frame:
        raise ValueError("This run keeps no member rankings (it predates them): cluster again once.")
    values = None
    if rank_by:
        activity = activity_values(self.runtime.workspace.project_db, rank_by)
        values = frame["molecule_id"].map(activity).to_numpy(dtype=float)
    labels = frame["cluster_id"].to_numpy()
    picks = pick_representatives(
        labels, frame["similarity"].to_numpy(), mode=mode, per_cluster=per_cluster, fraction=fraction,
        centrality=frame["centrality"].to_numpy(), values=values,
    )
    flags = np.zeros(len(frame), dtype=bool)
    flags[picks] = True
    picked_ids = [int(i) for i in frame["molecule_id"].to_numpy()[picks]]
    of_run = ClusteringResult.cluster_run_id == run_id
    if picked_ids and is_shard_key(picked_ids[0]):
        picked_ids = self._promote_picks(run_id, picked_ids, labels[picks])
    with self.runtime.workspace.project_db.get_session() as session:
        session.exec(sql_update(ClusteringResult).where(of_run).values(is_centroid=False))
        for start in range(0, len(picked_ids), 900):
            session.exec(
                sql_update(ClusteringResult)
                .where(of_run, ClusteringResult.molecule_id.in_(picked_ids[start:start + 900]))
                .values(is_centroid=True)
            )
        session.exec(sql_update(ClusteringRun).where(ClusteringRun.run_id == run_id).values(n_reps=len(picks)))
        session.commit()
    frame["is_centroid"] = flags
    frame.to_parquet(sidecar, index=False)
    return {"n_molecules": len(frame), "n_clusters": int(len(np.unique(labels))), "n_reps": len(picks)}

members_clause

members_clause(cluster_run_id: str, cluster_id: int | None = None)

Opaque SmartTable adapter: the molecules of one cluster, or the run's representatives when no cluster is given. A subquery, so it costs the same for 10 members or 10^6.

Source code in src/amdockvs/diversity/api.py
649
650
651
652
653
654
655
656
657
658
659
def members_clause(self, cluster_run_id: str, cluster_id: int | None = None):
    """Opaque SmartTable adapter: the molecules of one cluster, or the run's representatives
    when no cluster is given. A subquery, so it costs the same for 10 members or 10^6."""
    picked = select(ClusteringResult.molecule_id).where(
        ClusteringResult.cluster_run_id == str(cluster_run_id)
    )
    if cluster_id is None:
        picked = picked.where(ClusteringResult.is_centroid == True)  # noqa: E712 - SQL, not Python
    else:
        picked = picked.where(ClusteringResult.cluster_id == int(cluster_id))
    return MoleculeRecord.id.in_(picked)

exclude_non_representatives

exclude_non_representatives(cluster_run_id: str) -> int

Mark every non-representative of a run as excluded (the flag Filter uses; reversible). Returns how many were marked.

Source code in src/amdockvs/diversity/api.py
661
662
663
664
665
666
667
668
669
670
671
672
673
def exclude_non_representatives(self, cluster_run_id: str) -> int:
    """Mark every non-representative of a run as excluded (the flag Filter uses; reversible).
    Returns how many were marked."""
    self.runtime._require_active_project()
    non_reps = [r["molecule_id"] for r in self.get_run(cluster_run_id) if not r["is_centroid"]]
    if not non_reps:
        return 0
    with self.runtime.workspace.project_db.get_session() as session:
        run = session.exec(select(ClusteringRun).where(ClusteringRun.run_id == str(cluster_run_id))).first()
    detail = f"{run.method}, t={run.threshold}" if run is not None else str(cluster_run_id)[:8]
    return int(self.runtime.molecules.set_excluded_state(
        non_reps, excluded=True, reason=f"diversity: non-representative ({detail})"
    ))

save_selection_as_set

save_selection_as_set(molecule_ids: Iterable[int], *, name: str) -> MoleculeSetRef

Persist the chosen representatives as a molecule set (an enrichment set) so the rest of the app (docking, filter, export) can target the redundancy-reduced library.

Source code in src/amdockvs/diversity/api.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def save_selection_as_set(self, molecule_ids: Iterable[int], *, name: str) -> MoleculeSetRef:
    """Persist the chosen representatives as a molecule set (an enrichment set) so the rest of
    the app (docking, filter, export) can target the redundancy-reduced library."""
    self.runtime._require_active_project()
    ids = [int(i) for i in molecule_ids]
    if not ids:
        raise ValueError("No molecules to save as a set.")
    ref = create_snapshot_set(
        self.runtime.workspace.project_db,
        entity_kind="molecule",
        name=str(name).strip() or "diverse_selection",
        entity_ids=ids,
        kind=SetPurpose.ENRICHMENT,
    )
    return MoleculeSetRef(id=int(ref.id), kind="snapshot")

molblock_for

molblock_for(molecule_id: int) -> str | None

A 2-D-drawable molblock for one molecule (its stored structure), or None if there's no usable structure. Best-effort — used by the universe scatter's hover preview.

Source code in src/amdockvs/diversity/api.py
692
693
694
695
696
697
698
699
700
701
702
703
704
def molblock_for(self, molecule_id: int) -> str | None:
    """A 2-D-drawable molblock for one molecule (its stored structure), or None if there's
    no usable structure. Best-effort — used by the universe scatter's hover preview."""
    from rdkit import Chem

    from amdockvs.chemistry.structures import molecule_mol

    self.runtime._require_active_project()
    project_db = self.runtime.workspace.project_db
    with project_db.get_session() as session:
        rec = session.get(MoleculeRecord, int(molecule_id))
    mol = molecule_mol(project_db, rec, remove_hs=True) if rec is not None else None
    return Chem.MolToMolBlock(mol) if mol is not None else None

save_clustering_result

save_clustering_result(*, points: Iterable[tuple], cluster_stats: list[dict[str, Any]], evr: Iterable[float], method: str, threshold: float, scope_label: str, fp_radius: int = 2, fp_nbits: int = 2048, n_molecules: int | None = None, n_clusters: int | None = None, n_reps: int | None = None) -> str

Persist an applied clustering as a durable run: the graph points (x, y, molecule_id, cluster_id, is_centroid) to a parquet sidecar, and a compact ClusteringRun row (metadata + counts + the sidecar path). Returns the run id. Only the PCA + cluster flags are stored — fingerprints stay in their table, loaded by id if ever needed. Counts default to what the points imply; the parallel path passes them explicitly (it saves no graph sidecar yet).

Source code in src/amdockvs/diversity/api.py
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
def save_clustering_result(
    self,
    *,
    points: Iterable[tuple],
    cluster_stats: list[dict[str, Any]],
    evr: Iterable[float],
    method: str,
    threshold: float,
    scope_label: str,
    fp_radius: int = 2,
    fp_nbits: int = 2048,
    n_molecules: int | None = None,
    n_clusters: int | None = None,
    n_reps: int | None = None,
) -> str:
    """Persist an applied clustering as a durable run: the graph points (x, y, molecule_id,
    cluster_id, is_centroid) to a parquet sidecar, and a compact ``ClusteringRun`` row (metadata
    + counts + the sidecar path). Returns the run id. Only the PCA + cluster flags are stored —
    fingerprints stay in their table, loaded by id if ever needed. Counts default to what the
    points imply; the parallel path passes them explicitly (it saves no graph sidecar yet)."""
    import pandas as pd

    self.runtime._require_active_project()
    run_id = uuid.uuid4().hex
    snap_dir = self._project_root() / "clustering_runs"
    snap_dir.mkdir(parents=True, exist_ok=True)
    snapshot = snap_dir / f"{run_id}.parquet"
    frame = pd.DataFrame(
        list(points), columns=["x", "y", "molecule_id", "cluster_id", "is_centroid"]
    )
    frame.to_parquet(snapshot, index=False)
    row = ClusteringRun(
        run_id=run_id, method=str(method), threshold=float(threshold), scope_label=str(scope_label),
        fp_radius=int(fp_radius), fp_nbits=int(fp_nbits),
        n_molecules=int(n_molecules if n_molecules is not None else len(frame)),
        n_clusters=int(n_clusters if n_clusters is not None else len(cluster_stats or [])),
        n_reps=int(n_reps if n_reps is not None else (frame["is_centroid"].sum() if len(frame) else 0)),
        snapshot_path=str(snapshot), evr=list(evr or [0.0, 0.0]), cluster_stats=list(cluster_stats or []),
    )
    with self.runtime.workspace.project_db.get_session() as session:
        session.add(row)
        session.commit()
    return run_id

list_clustering_results

list_clustering_results() -> list[dict[str, Any]]

Saved runs, newest first — for the results table.

Source code in src/amdockvs/diversity/api.py
757
758
759
760
761
762
763
764
765
766
767
def list_clustering_results(self) -> list[dict[str, Any]]:
    """Saved runs, newest first — for the results table."""
    self.runtime._require_active_project()
    with self.runtime.workspace.project_db.get_session() as session:
        rows = session.exec(select(ClusteringRun).order_by(ClusteringRun.id.desc())).all()
    return [
        {"run_id": r.run_id, "created_at": r.created_at, "method": r.method, "threshold": r.threshold,
         "scope_label": r.scope_label, "n_molecules": r.n_molecules, "n_clusters": r.n_clusters,
         "n_reps": r.n_reps}
        for r in rows
    ]

load_clustering_result

load_clustering_result(run_id: str) -> dict[str, Any]

Everything needed to redraw a saved run (graph points + cluster stats + evr) — read the sidecar directly, no re-clustering or PCA recompute.

Source code in src/amdockvs/diversity/api.py
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
def load_clustering_result(self, run_id: str) -> dict[str, Any]:
    """Everything needed to redraw a saved run (graph points + cluster stats + evr) — read the
    sidecar directly, no re-clustering or PCA recompute."""
    import pandas as pd

    self.runtime._require_active_project()
    with self.runtime.workspace.project_db.get_session() as session:
        row = session.exec(select(ClusteringRun).where(ClusteringRun.run_id == str(run_id))).first()
    if row is None:
        raise ValueError(f"Unknown clustering run: {run_id}")
    if row.snapshot_path and Path(row.snapshot_path).exists():
        frame = pd.read_parquet(row.snapshot_path)
    else:
        frame = pd.DataFrame(columns=["x", "y", "molecule_id", "cluster_id", "is_centroid"])
    return {
        "run_id": row.run_id, "method": row.method, "threshold": row.threshold,
        "scope_label": row.scope_label, "n_molecules": row.n_molecules, "n_clusters": row.n_clusters,
        # Runs registered before the variance was kept stored exactly [0.0, 0.0]; no real
        # projection explains nothing on both axes, so that reads as "not recorded".
        "n_reps": row.n_reps, "evr": list(row.evr) if any(row.evr or []) else [],
        "cluster_stats": list(row.cluster_stats or []), "points": frame.to_dict("records"),
    }

External tools

ToolAPI dataclass

ToolAPI(runtime: Any)

Methods:

Name Description
status

Return the current readiness of one managed tool, or every tool.

install

Install a tool if needed and return its verified status.

uninstall

Remove a managed tool from disk.

repair

Remove and reinstall a tool whose on-disk installation is suspect.

status

status(tool_id: str | None = None) -> ToolStatus | tuple[ToolStatus, ...]

Return the current readiness of one managed tool, or every tool.

Source code in src/amdockvs/integrations/api.py
22
23
24
25
26
def status(self, tool_id: str | None = None) -> ToolStatus | tuple[ToolStatus, ...]:
    """Return the current readiness of one managed tool, or every tool."""
    if tool_id is None:
        return tuple(tool_statuses(self.runtime))
    return get_tool(tool_id).status(self.runtime)

install

install(tool_id: str) -> ToolStatus

Install a tool if needed and return its verified status.

Source code in src/amdockvs/integrations/api.py
28
29
30
31
32
33
34
35
36
def install(self, tool_id: str) -> ToolStatus:
    """Install a tool if needed and return its verified status."""
    current = self.status(tool_id)
    assert isinstance(current, ToolStatus)
    if not current.installed:
        run_steps(install_steps(self.runtime, tool_id))
    result = self.status(tool_id)
    assert isinstance(result, ToolStatus)
    return result

uninstall

uninstall(tool_id: str) -> str

Remove a managed tool from disk.

Source code in src/amdockvs/integrations/api.py
38
39
40
def uninstall(self, tool_id: str) -> str:
    """Remove a managed tool from disk."""
    return uninstall_tool(self.runtime, tool_id)

repair

repair(tool_id: str) -> ToolStatus

Remove and reinstall a tool whose on-disk installation is suspect.

Source code in src/amdockvs/integrations/api.py
42
43
44
45
def repair(self, tool_id: str) -> ToolStatus:
    """Remove and reinstall a tool whose on-disk installation is suspect."""
    self.uninstall(tool_id)
    return self.install(tool_id)