Source code for jcmsuite.torch.core

"""Solve orchestration for the optional Torch integration."""

from __future__ import annotations

import asyncio
from collections.abc import Callable, Coroutine, Mapping, Sequence
from typing import Literal, TypeAlias, Unpack, cast, overload

from jcmsuite.context import BackendMode, SolverContext
from jcmsuite.results import (
    Resultbag,
)
from jcmsuite.solve.solver import solve as ordinary_solve
from jcmsuite.solve.types import (
    BatchOnError,
    BatchSolveKeysInput,
    DispatchMode,
    ProjectBundleInput,
    ProjectPathInput,
    SolveKeysInput,
    WaitBreakWhen,
    WaitOnTimeout,
    WorkingDirInput,
)

from .results import (
    TorchBatchSolveResult,
    TorchBatchSolveSubmission,
    TorchBundledBatchSolveResult,
    TorchBundledBatchSolveSubmission,
    TorchBundledSolveResult,
    TorchBundledSolveSubmission,
    TorchSolveResult,
    TorchSolveSubmission,
)
from .types import BindingContext, BindingMap, InputContext, TorchSolveOptions
from .validation import (
    binding_inputs,
    detached_keys,
    load_torch,
    validate_bundle_inputs,
    validate_inputs,
)
from .wrappers import wrap_result

TorchSolveReturn: TypeAlias = (
    TorchSolveResult
    | TorchBatchSolveResult
    | TorchBundledSolveResult
    | TorchBundledBatchSolveResult
    | TorchSolveSubmission
    | TorchBatchSolveSubmission
    | TorchBundledSolveSubmission
    | TorchBundledBatchSolveSubmission
)


@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: SolveKeysInput = None,
    dispatch: Literal["wait"] = "wait",
    asynchronous: Literal[False] = False,
    **options: Unpack[TorchSolveOptions],
) -> TorchSolveResult: ...
@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: BatchSolveKeysInput,
    dispatch: Literal["wait"] = "wait",
    asynchronous: Literal[False] = False,
    **options: Unpack[TorchSolveOptions],
) -> TorchBatchSolveResult: ...
@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: SolveKeysInput = None,
    dispatch: Literal["submit"],
    asynchronous: Literal[False] = False,
    **options: Unpack[TorchSolveOptions],
) -> TorchSolveSubmission: ...
@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: BatchSolveKeysInput,
    dispatch: Literal["submit"],
    asynchronous: Literal[False] = False,
    **options: Unpack[TorchSolveOptions],
) -> TorchBatchSolveSubmission: ...
@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: SolveKeysInput = None,
    dispatch: Literal["wait"] = "wait",
    asynchronous: Literal[False] = False,
    **options: Unpack[TorchSolveOptions],
) -> TorchBundledSolveResult: ...
@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: BatchSolveKeysInput,
    dispatch: Literal["wait"] = "wait",
    asynchronous: Literal[False] = False,
    **options: Unpack[TorchSolveOptions],
) -> TorchBundledBatchSolveResult: ...
@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: SolveKeysInput = None,
    dispatch: Literal["submit"],
    asynchronous: Literal[False] = False,
    **options: Unpack[TorchSolveOptions],
) -> TorchBundledSolveSubmission: ...
@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: BatchSolveKeysInput,
    dispatch: Literal["submit"],
    asynchronous: Literal[False] = False,
    **options: Unpack[TorchSolveOptions],
) -> TorchBundledBatchSolveSubmission: ...
@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: SolveKeysInput = None,
    dispatch: DispatchMode = "wait",
    asynchronous: Literal[True],
    **options: Unpack[TorchSolveOptions],
) -> Coroutine[object, object, TorchSolveResult | TorchSolveSubmission]: ...
@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: BatchSolveKeysInput,
    dispatch: DispatchMode = "wait",
    asynchronous: Literal[True],
    **options: Unpack[TorchSolveOptions],
) -> Coroutine[object, object, TorchBatchSolveResult | TorchBatchSolveSubmission]: ...
@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: SolveKeysInput = None,
    dispatch: DispatchMode = "wait",
    asynchronous: Literal[True],
    **options: Unpack[TorchSolveOptions],
) -> Coroutine[
    object, object, TorchBundledSolveResult | TorchBundledSolveSubmission
]: ...
@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: BatchSolveKeysInput,
    dispatch: DispatchMode = "wait",
    asynchronous: Literal[True],
    **options: Unpack[TorchSolveOptions],
) -> Coroutine[
    object,
    object,
    TorchBundledBatchSolveResult | TorchBundledBatchSolveSubmission,
]: ...
[docs] def solve( project_file: ProjectPathInput | ProjectBundleInput, *, keys: SolveKeysInput | BatchSolveKeysInput = None, resultbag: Resultbag | None = None, recompute: bool = False, max_retries: int = 0, on_error: BatchOnError = "raise", context: SolverContext | None = None, backend: BackendMode | None = None, working_dir: WorkingDirInput = None, jcmt_pattern: str | None = None, temporary: bool = False, dispatch: DispatchMode = "wait", wait_break_when: WaitBreakWhen = "all", wait_timeout: float | None = None, wait_on_timeout: WaitOnTimeout = "raise", wait_progress: bool = False, wait_progress_label: str | None = None, quiet: bool = False, asynchronous: bool = False, key_derivative_map: BindingMap | Sequence[BindingMap] | None = None, ) -> TorchSolveReturn | Coroutine[object, object, TorchSolveReturn]: """Connect solver derivatives to Torch project keys in a solve. All ordinary solve options and execution behavior follow :func:`~jcmsuite.solve`. Only Torch-specific inputs and return differences are described here. See :func:`~jcmsuite.torch.validate_inputs` for binding validation. Parameters ---------- keys : SolveKeysInput | BatchSolveKeysInput, optional Project keys may contain scalar Torch tensors with ``requires_grad=True``. Each such tensor needs a derivative binding. Fixed values use the ordinary project key behavior. key_derivative_map : BindingMap | Sequence[BindingMap] | None, optional Bind each gradient-enabled project key name to a solver derivative label with :class:`~jcmsuite.torch.RealDerivative` or to two labels with :class:`~jcmsuite.torch.ComplexDerivative`. Use one mapping for a single project or one mapping per project in an ordered project bundle. Returns ------- TorchSolveReturn | Coroutine[object, object, TorchSolveReturn] The shape-specific Torch result or submission wrapper. One project returns :class:`~jcmsuite.torch.results.TorchSolveResult` or :class:`~jcmsuite.torch.results.TorchBatchSolveResult` for batched project keys. An ordered project bundle returns :class:`~jcmsuite.torch.results.TorchBundledSolveResult` or :class:`~jcmsuite.torch.results.TorchBundledBatchSolveResult`. With ``dispatch="submit"``, the corresponding :class:`~jcmsuite.torch.results.TorchSolveSubmission`, :class:`~jcmsuite.torch.results.TorchBatchSolveSubmission`, :class:`~jcmsuite.torch.results.TorchBundledSolveSubmission`, or :class:`~jcmsuite.torch.results.TorchBundledBatchSolveSubmission` is returned. With ``asynchronous=True``, await the coroutine to obtain that wrapper. Use :meth:`~jcmsuite.torch.results.TorchSolveResult.untorch` (or the corresponding wrapper method) to access the underlying ordinary result or submission without recomputing the solve. """ torch_module: object = load_torch() if isinstance(keys, Mapping): if isinstance(key_derivative_map, Mapping) or key_derivative_map is None: bindings: BindingMap = cast(BindingMap, key_derivative_map or {}) validate_inputs(keys, bindings) binding_context: BindingContext = bindings else: maps: tuple[BindingMap, ...] = tuple(key_derivative_map) if not isinstance(project_file, (list, tuple)): raise ValueError("Derivative maps are scoped only for ordered bundles.") validate_bundle_inputs(keys, maps) binding_context = maps inputs: InputContext = ( tuple( binding_inputs(keys, binding_map, torch_module) for binding_map in binding_context ) if isinstance(binding_context, tuple) else binding_inputs(keys, binding_context, torch_module) ) else: binding_context = ( cast(BindingContext, key_derivative_map) if isinstance(key_derivative_map, Mapping) else tuple(key_derivative_map or ()) ) inputs = () if keys is not None: for entry in keys: if isinstance(binding_context, Mapping): validate_inputs(entry, binding_context) else: validate_bundle_inputs(entry, binding_context) if isinstance(binding_context, Mapping): inputs = tuple( binding_inputs(entry, binding_context, torch_module) for entry in keys ) elif keys: inputs = tuple( tuple( binding_inputs(entry, binding_map, torch_module) for entry in keys ) for binding_map in binding_context ) ordinary: object = cast(Callable[..., object], ordinary_solve)( project_file, keys=cast( SolveKeysInput | BatchSolveKeysInput, detached_keys(keys, torch_module) ), resultbag=resultbag, recompute=recompute, max_retries=max_retries, on_error=on_error, context=context, backend=backend, working_dir=working_dir, jcmt_pattern=jcmt_pattern, temporary=temporary, dispatch=dispatch, wait_break_when=wait_break_when, wait_timeout=wait_timeout, wait_on_timeout=wait_on_timeout, wait_progress=wait_progress, wait_progress_label=wait_progress_label, quiet=quiet, asynchronous=asynchronous, ) if asynchronous and asyncio.iscoroutine(ordinary): async def bind_async() -> object: return wrap_result(await ordinary, binding_context, inputs, torch_module) return cast(Coroutine[object, object, TorchSolveReturn], bind_async()) return cast( TorchSolveReturn, wrap_result(ordinary, binding_context, inputs, torch_module) )
__all__ = ["solve"]