Torch

This page describes the optional jcmsuite.torch namespace. See jcmsuite.solve() for the shared solve options. See the Result API for result navigation and submission behavior. For examples, see Torch Integration.

Install PyTorch before you call jcmsuite.torch.solve() or jcmsuite.torch.validate_inputs(). Ordinary jcmsuite operations do not require PyTorch.

Experimental feature

The jcmsuite.torch integration is experimental. Its API and behavior can change in future releases. Do not depend on its current interface for production workflows without testing each package update.

Bind Inputs To Solver Derivatives

Use RealDerivative for a real input. Use ComplexDerivative when the real and imaginary parts of a complex input have separate solver derivatives. Both types are DerivativeBinding values.

jcmsuite.torch.DerivativeBinding

alias of RealDerivative | ComplexDerivative

class jcmsuite.torch.SolverDerivative[source]

Store explicit solver derivative metadata.

class jcmsuite.torch.RealDerivative(label)[source]

Bind one real project key to one solver derivative label.

Pass this binding through key_derivative_map to solve().

label

Solver derivative label for the real project key.

Type:

str

class jcmsuite.torch.ComplexDerivative(real, imaginary)[source]

Bind one complex project key to two solver derivative labels.

Pass this binding through key_derivative_map to solve().

real

Solver derivative label for the real input direction.

Type:

str

imaginary

Solver derivative label for the imaginary input direction.

Type:

str

Call jcmsuite.torch.validate_inputs() to check one set of project keys and its derivative bindings before a solve.

jcmsuite.torch.validate_inputs(keys, key_derivative_map)[source]

Validate one solve’s Torch inputs and derivative bindings.

Parameters:
  • keys (Mapping[str, object]) – Project keys supplied to one solve entry.

  • key_derivative_map (BindingMap) – Bindings from gradient-enabled project key names to solver derivative labels, using RealDerivative or ComplexDerivative.

Raises:
  • ImportError – If PyTorch is not installed.

  • ValueError – If a binding is missing, unknown, invalid, duplicated, or incompatible with the project key tensor dtype or device.

Solve

jcmsuite.torch.solve() accepts the parameters of jcmsuite.solve(). You can also pass Torch tensors as keys and use key_derivative_map to connect them to solver derivatives. The function returns a Torch result or submission object. See jcmsuite.solve() for shared options and errors. The type hints show the return object for each input shape.

jcmsuite.torch.solve(project_file, *, keys=None, resultbag=None, recompute=False, max_retries=0, on_error='raise', context=None, backend=None, working_dir=None, jcmt_pattern=None, temporary=False, dispatch='wait', wait_break_when='all', wait_timeout=None, wait_on_timeout='raise', wait_progress=False, wait_progress_label=None, quiet=False, asynchronous=False, key_derivative_map=None)[source]

Connect solver derivatives to Torch project keys in a solve.

All ordinary solve options and execution behavior follow solve(). Only Torch-specific inputs and return differences are described here. See 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 RealDerivative or to two labels with ComplexDerivative. Use one mapping for a single project or one mapping per project in an ordered project bundle.

Returns:

The shape-specific Torch result or submission wrapper. One project returns TorchSolveResult or TorchBatchSolveResult for batched project keys. An ordered project bundle returns TorchBundledSolveResult or TorchBundledBatchSolveResult. With dispatch="submit", the corresponding TorchSolveSubmission, TorchBatchSolveSubmission, TorchBundledSolveSubmission, or TorchBundledBatchSolveSubmission is returned. With asynchronous=True, await the coroutine to obtain that wrapper. Use untorch() (or the corresponding wrapper method) to access the underlying ordinary result or submission without recomputing the solve.

Return type:

TorchSolveReturn | Coroutine[object, object, TorchSolveReturn]

Result And Submission Types

The project and project keys determine the result type. The table shows each ordinary result, its Torch wrapper, and the method that returns the ordinary result without solving again.

Ordinary result

Torch result

Get ordinary result

SolveResult

TorchSolveResult

untorch()

BatchSolveResult

TorchBatchSolveResult

untorch()

BundledSolveResult

TorchBundledSolveResult

untorch()

BundledBatchSolveResult

TorchBundledBatchSolveResult

untorch()

With dispatch="submit", the solve returns a Torch submission. Call wait() to get a Torch result of the same shape. Each wait() accepts the options of the matching ordinary submission. With asynchronous=True, await the returned coroutine. Each submission’s untorch() returns its ordinary submission without running the solve again. The result wrappers’ untorch() methods return ordinary results.

Torch submission

Wait for a Torch result

Get ordinary submission

TorchSolveSubmission

wait()

untorch()

TorchBatchSolveSubmission

wait()

untorch()

TorchBundledSolveSubmission

wait()

untorch()

TorchBundledBatchSolveSubmission

wait()

untorch()

class jcmsuite.torch.results.TorchSolveResult(result, bindings, inputs, torch_module)[source]

Wrap a SolveResult with Torch-aware access.

untorch()[source]

Return the underlying single-project result without recomputing it.

Returns:

The ordinary SolveResult.

Return type:

SolveResult

property postprocesses

Return the Torch-aware single-result postprocess collection.

class jcmsuite.torch.results.TorchBatchSolveResult(result, bindings, inputs, torch_module)[source]

Wrap a BatchSolveResult with Torch-aware access.

untorch()[source]

Return the underlying batched result without recomputing it.

Returns:

The ordinary BatchSolveResult.

Return type:

BatchSolveResult

property postprocesses

Return the Torch-aware aggregate batch postprocess collection.

class jcmsuite.torch.results.TorchBundledSolveResult(result, bindings, inputs, torch_module)[source]

Wrap a BundledSolveResult with Torch-aware access.

untorch()[source]

Return the underlying ordered-bundle result without recomputing it.

Returns:

The ordinary BundledSolveResult.

Return type:

BundledSolveResult

class jcmsuite.torch.results.TorchBundledBatchSolveResult(result, bindings, inputs, torch_module)[source]

Wrap a BundledBatchSolveResult with Torch-aware access.

untorch()[source]

Return the underlying bundled-batch result without recomputing it.

Returns:

The ordinary BundledBatchSolveResult.

Return type:

BundledBatchSolveResult

class jcmsuite.torch.results.TorchSolveSubmission(submission, bindings, inputs, torch_module)[source]

Wrap a SolveSubmission.

untorch()[source]

Return the ordinary single-project submission without recomputing it.

Returns:

The underlying SolveSubmission.

Return type:

SolveSubmission

wait(**kwargs)[source]

Wait for a single-project Torch result.

Parameters:

kwargs (object) – Options accepted by wait(). Use asynchronous=True to receive a coroutine.

Returns:

The TorchSolveResult, or a coroutine that resolves to it.

Return type:

TorchSolveResult | Coroutine[object, object, TorchSolveResult]

class jcmsuite.torch.results.TorchBatchSolveSubmission(submission, bindings, inputs, torch_module)[source]

Wrap a BatchSolveSubmission.

untorch()[source]

Return the ordinary batched submission without recomputing it.

Returns:

The underlying BatchSolveSubmission.

Return type:

BatchSolveSubmission

wait(**kwargs)[source]

Wait for a batched Torch result.

Parameters:

kwargs (object) – Options accepted by wait(). Use asynchronous=True to receive a coroutine.

Returns:

The TorchBatchSolveResult, or a coroutine that resolves to it.

Return type:

TorchBatchSolveResult | Coroutine[object, object, TorchBatchSolveResult]

class jcmsuite.torch.results.TorchBundledSolveSubmission(submission, bindings, inputs, torch_module)[source]

Wrap a BundledSolveSubmission.

untorch()[source]

Return the ordinary ordered-bundle submission without recomputing it.

Returns:

The underlying BundledSolveSubmission.

Return type:

BundledSolveSubmission

wait(**kwargs)[source]

Wait for an ordered-bundle Torch result.

Parameters:

kwargs (object) – Options accepted by wait(). Use asynchronous=True to receive a coroutine.

Returns:

The TorchBundledSolveResult, or a coroutine that resolves to it.

Return type:

TorchBundledSolveResult | Coroutine[object, object, TorchBundledSolveResult]

class jcmsuite.torch.results.TorchBundledBatchSolveSubmission(submission, bindings, inputs, torch_module)[source]

Wrap a BundledBatchSolveSubmission.

untorch()[source]

Return the ordinary bundled-batch submission without recomputing it.

Returns:

The underlying BundledBatchSolveSubmission.

Return type:

BundledBatchSolveSubmission

wait(**kwargs)[source]

Wait for a bundled-batch Torch result.

Parameters:

kwargs (object) – Options accepted by wait(). Use asynchronous=True to receive a coroutine.

Returns:

The TorchBundledBatchSolveResult, or a coroutine that resolves to it.

Return type:

TorchBundledBatchSolveResult | Coroutine[object, object, TorchBundledBatchSolveResult]

Export Limits

TorchPostprocessRecord and TorchFieldExportPayload reject to_df() and to_xarray() because these exports cannot preserve Torch autograd connections. Call untorch() on the solve result, then use the ordinary result export methods.

Navigate Postprocess Data

Public Torch-aware result and submission wrappers.

The postprocess collection and record wrappers mirror the corresponding ordinary result interfaces. Batch wrappers also preserve the ordinary batch navigation and field operations. Select a project before accessing results from an ordered project bundle. Other result data, such as keys and costs, keeps its ordinary form.

The single-result collection returns TorchPostprocessRecord values. A batch collection returns TorchBatchPostprocessRecord values. Batch dictionary exports keep original batch indices. Each available entry returns Torch tensors connected to that entry’s input tensors when the solver provides the required derivatives. Transformed batch field exports use the Torch field wrapper’s derivative rules.

Postprocess dictionaries omit raw derivative branches. Numeric values without solver derivative data become detached Torch tensors.

Expression

Returned object

TorchSolveResult.postprocesses

TorchPostprocessCollection

TorchPostprocessCollection[index]

TorchPostprocessRecord

TorchPostprocessRecord.fields

TorchFieldExportPayload when the postprocess contains field data

class jcmsuite.torch.results.TorchPostprocessCollection(collection, bindings, inputs, torch_module)[source]

Provide Torch-aware access to a result’s postprocess records.

Indexing or iteration returns TorchPostprocessRecord values. For the navigation and export contract shared with ordinary results, see jcmsuite.results.PostprocessCollection.

This class is returned by result accessors. Do not construct it directly.

__getitem__(index)[source]

Return one Torch postprocess record by its integer position.

Parameters:

index (int) – Postprocess position.

Returns:

Selected Torch-aware record.

Return type:

TorchPostprocessRecord

__iter__()[source]

Iterate over Torch postprocess records in project order.

Returns:

Torch-aware records in postprocess order.

Return type:

Iterator[TorchPostprocessRecord]

__len__()[source]

Return the number of postprocess records.

Returns:

Number of postprocess records.

Return type:

int

titles()[source]

Return postprocess titles in project order.

Returns:

Titles in postprocess order.

Return type:

tuple[str, …]

class jcmsuite.torch.results.TorchPostprocessRecord(record, bindings, inputs, torch_module, transforms=())[source]

Wrap one ordinary postprocess record with Torch-aware exports.

Use fields to get the field-export interface when the postprocess contains field data. Other postprocess data is available through to_dict(). The class is returned by TorchPostprocessCollection; do not construct it directly.

to_df(orient=None)

Raise because Torch tensor payloads do not support DataFrame export.

Parameters:

orient (str | None, optional) – DataFrame orientation. The value does not change the error.

Returns:

This method does not return.

Return type:

object

Raises:

UnsupportedExportError – Always. Use the ordinary solve result for DataFrame export.

to_dict()

Return the payload as a mapping with Torch numeric leaves.

Returns:

The ordinary mapping with numeric leaves converted to Torch tensors. Leaves with solver derivative data remain connected to the bound inputs; numeric leaves without derivative data are detached.

Return type:

Mapping[object, object]

to_xarray()

Raise because Torch tensor payloads do not support xarray export.

Returns:

This method does not return.

Return type:

object

Raises:

UnsupportedExportError – Always. Use the ordinary solve result for xarray export.

property derivatives

Return derivative navigation for this postprocess result.

property fields

Return the field-export view for this postprocess.

Returns:

Torch-aware field navigation and export.

Return type:

TorchFieldExportPayload

Batch Postprocess and Field Classes

Expression

Returned object

TorchBatchSolveResult.postprocesses

TorchBatchPostprocessCollection

TorchBatchPostprocessCollection[index]

TorchBatchPostprocessRecord

batch record.fields

TorchBatchFieldExportPayload when the postprocess contains field data

batch field.base, field.select(index), or field.transform(name)

TorchBatchFieldExportPayload

batch field.intensity

TorchBatchIntensityFieldExportPayload

batch field.derivatives

TorchBatchFieldDerivativeCollection

batch field.derivatives[name] for a real input

TorchBatchFieldDerivativePayload

batch field.derivatives[name] for a complex input

TorchBatchComplexFieldDerivativePayload with .real and optional .imag batch payloads

class jcmsuite.torch.results.TorchBatchPostprocessCollection(collection, bindings, inputs, torch_module)[source]

Provide Torch-aware access to postprocess streams across a batch.

The ordinary jcmsuite.results.BatchPostprocessCollection defines the batch navigation. This wrapper adds the Torch semantics of TorchPostprocessCollection to each selected record.

A Torch batch solve result returns this class. Do not construct it directly.

__getitem__(index)[source]

Return one batch postprocess stream.

Parameters:

index (int) – Postprocess position.

Returns:

Selected batch record with entry-specific input contexts.

Return type:

TorchBatchPostprocessRecord

__iter__()[source]

Iterate over batch postprocess streams in project order.

Returns:

Torch-aware records in postprocess order.

Return type:

Iterator[TorchBatchPostprocessRecord]

__len__()[source]

Return the number of postprocess streams.

Returns:

Number of postprocess streams.

Return type:

int

titles()[source]

Return postprocess titles in project order.

Returns:

Titles from the ordinary batch collection.

Return type:

tuple[str, …]

class jcmsuite.torch.results.TorchBatchPostprocessRecord(record, bindings, inputs, torch_module)[source]

Wrap one postprocess stream across a batch.

The ordinary jcmsuite.results.BatchPostprocessRecord defines its batch navigation and export structure. This wrapper adds the Torch semantics of TorchPostprocessRecord to each available entry, including tensor conversion and entry-specific autograd connections.

The collection returns this class. Do not construct it directly.

to_df(orient=None)

Raise because Torch tensor payloads do not support DataFrame export.

Parameters:

orient (str | None, optional) – DataFrame orientation. The value does not change the error.

Returns:

This method does not return.

Return type:

object

Raises:

UnsupportedExportError – Always. Use the ordinary solve result for DataFrame export.

to_dict()[source]

Return one Torch-aware postprocess mapping per available batch entry.

The outer mapping uses original batch indices. Each value follows the single-result TorchPostprocessRecord.to_dict() contract. Numeric values with solver derivatives connect to that entry’s input tensors.

Returns:

Available postprocess mappings keyed by original batch index.

Return type:

Mapping[object, object]

to_xarray()

Raise because Torch tensor payloads do not support xarray export.

Returns:

This method does not return.

Return type:

object

Raises:

UnsupportedExportError – Always. Use the ordinary solve result for xarray export.

property fields

Return the aggregate field view with per-entry Torch contexts.

Returns:

Batch field navigation and Torch-aware dictionary export.

Return type:

TorchBatchFieldExportPayload

class jcmsuite.torch.results.TorchBatchFieldExportPayload(payload, bindings, inputs, torch_module, transforms=())[source]

Provide Torch-aware dictionary exports for fields across a batch.

The ordinary jcmsuite.results.BatchFieldExportPayload defines the batch navigation and export structure. This wrapper adds the Torch field semantics of TorchFieldExportPayload to each available entry. Operations retain original batch indices. The to_dict() method returns one mapping per available entry and converts numeric values to Torch tensors. Solver derivatives connect each tensor to its matching input.

The derivatives property returns a Torch-specific lookup keyed by bound project key name. Each derivative export uses that entry’s derivative bindings and remains keyed by original batch index. The collection is empty when no differentiable inputs are bound.

A Torch batch postprocess record returns this class. Do not construct it directly.

__getitem__(key)[source]

Select a named field quantity across the batch.

Parameters:

key (object) – Field quantity name or nested mapping key.

Returns:

Selected fields with original batch indices.

Return type:

TorchBatchFieldExportPayload

select(index=None)[source]

Select a field position across available batch entries.

Parameters:

index (int | None, optional) – Field position. None selects all field positions.

Returns:

Selected fields with original batch indices.

Return type:

TorchBatchFieldExportPayload

to_df(orient=None)[source]

Raise because Torch-bound batch fields do not support DataFrame export.

Parameters:

orient (str | None, optional) – DataFrame orientation. The value does not change the error.

Returns:

This method does not return.

Return type:

object

Raises:

UnsupportedExportError – Always. Use the underlying ordinary batch result for DataFrame export.

to_dict()[source]

Return field mappings keyed by original batch index.

Each available entry is converted by the single-result field wrapper. Numeric field values are Torch tensors. When solver derivatives are available, each field tensor connects to the matching entry’s input tensors. Field transforms apply the same derivative rules as the single-result Torch field wrapper.

Returns:

Available field mappings keyed by original batch index.

Return type:

Mapping[int, Mapping[object, object]]

to_xarray()[source]

Raise because Torch-bound batch fields do not support xarray export.

Returns:

This method does not return.

Return type:

object

Raises:

UnsupportedExportError – Always. Use the underlying ordinary batch result for xarray export.

transform(name)[source]

Transform fields across the batch and retain input gradients.

Parameters:

name (str) – One of "abs", "real", "imag", or "phase".

Returns:

Transformed fields with original batch indices.

Return type:

TorchBatchFieldExportPayload

Raises:
  • ValueError – If name is not supported.

  • AttributeError – If this is an intensity view.

property base

Return the batch field view without solver derivative branches.

Returns:

Base fields for all available batch entries.

Return type:

TorchBatchFieldExportPayload

property derivatives

Return binding-aware solver derivative lookup across the batch.

Returns:

Derivative lookup by differentiable project key name. A lookup returns detached Torch derivative mappings keyed by original batch index. The collection is empty when no differentiable inputs are bound.

Return type:

TorchBatchFieldDerivativeCollection

property intensity

Return the squared-norm intensity view for the batch.

Returns:

Non-transformable intensity fields for all available batch entries.

Return type:

TorchBatchIntensityFieldExportPayload

class jcmsuite.torch.results.TorchBatchIntensityFieldExportPayload(view)[source]

Provide a non-transformable Torch intensity view across a batch.

This wrapper mirrors TorchIntensityFieldExportPayload over the ordinary jcmsuite.results.BatchIntensityFieldExportPayload. Dictionary exports retain original batch indices and connect each entry to its matching input when solver derivatives are available.

TorchBatchFieldExportPayload.intensity returns this class. Do not construct it directly.

__getitem__(key)[source]

Select a named intensity field quantity across the batch.

Parameters:

key (object) – Field quantity name or nested mapping key.

Returns:

Selected intensity fields with original batch indices.

Return type:

TorchBatchIntensityFieldExportPayload

select(index=None)[source]

Select field positions across the batch.

Parameters:

index (int | None, optional) – Field position. None selects all positions.

Returns:

Selected intensity fields with original batch indices.

Return type:

TorchBatchIntensityFieldExportPayload

to_df(orient=None)[source]

Raise because Torch intensity fields do not support DataFrame export.

Parameters:

orient (str | None, optional) – DataFrame orientation. The value does not change the error.

Returns:

This method does not return.

Return type:

object

Raises:

UnsupportedExportError – Always. Use the ordinary batch result for DataFrame export.

to_dict()[source]

Return Torch intensity dictionaries keyed by original batch index.

Returns:

Available intensity mappings. Solver derivatives connect each intensity tensor to its matching input tensor.

Return type:

Mapping[int, Mapping[object, object]]

to_xarray()[source]

Raise because Torch intensity fields do not support xarray export.

Returns:

This method does not return.

Return type:

object

Raises:

UnsupportedExportError – Always. Use the ordinary batch result for xarray export.

property base

Return the intensity view without solver derivative branches.

Returns:

Base intensity fields for available batch entries.

Return type:

TorchBatchIntensityFieldExportPayload

property derivatives

Return binding-aware derivatives for the batch intensity.

Returns:

Derivative lookup keyed by differentiable project key name. Each payload retains original batch indices.

Return type:

TorchBatchFieldDerivativeCollection

class jcmsuite.torch.results.TorchBatchFieldDerivativeCollection(owner)[source]

Look up solver field derivatives by bound project key across a batch.

This collection composes the lookup behavior of TorchFieldDerivativeCollection with the original-index alignment of ordinary batch field payloads. Each lookup collects the corresponding single-entry Torch derivative and retains only entries with available field data and bindings.

A Torch batch field payload returns this collection. Do not construct it directly.

__getitem__(name)[source]

Return one bound solver derivative for each available batch entry.

Parameters:

name (str) – Differentiable project key name.

Returns:

Detached field derivatives keyed by original batch index.

Return type:

TorchBatchFieldDerivativePayload | TorchBatchComplexFieldDerivativePayload

Raises:

KeyError – If name is not bound to a differentiable input.

keys()[source]

Return bound project key names available in the batch.

Returns:

Bound names in first-seen order across available batch field entries.

Return type:

tuple[str, …]

class jcmsuite.torch.results.TorchBatchFieldDerivativePayload(entries)[source]

Provide field sensitivities keyed by original batch index.

This payload composes the dictionary and selection behavior of TorchFieldDerivativePayload across available batch entries. Its to_dict() method returns each single-entry derivative mapping under the original batch index.

First sensitivities remain differentiable when all required second-order pairs are available. Without second-order data, they are detached values. Partial pair data raises an error when exporting a first sensitivity. Selected second-order values are detached.

A lookup in TorchBatchFieldDerivativeCollection returns this payload for a real input. Do not construct it directly.

select(index=None)[source]

Select one field position in every available batch entry.

Parameters:

index (int | None, optional) – Field position. None selects all positions.

Returns:

Selected derivatives with original batch indices.

Return type:

TorchBatchFieldDerivativePayload

to_dict()[source]

Return derivative mappings for available batch entries.

Returns:

Derivative mappings keyed by original batch index.

Return type:

Mapping[int, Mapping[object, object]]

property derivatives

Return nested solver derivatives aligned by original batch index.

Each available entry is navigated independently. Missing and failed entries remain absent; they are never filled from a neighboring entry.

class jcmsuite.torch.results.TorchBatchComplexFieldDerivativePayload(real, imag)[source]

Store packed output-component derivatives across a batch.

This payload composes the component behavior of TorchComplexFieldDerivativePayload across batch entries. The real and optional imag values are batch derivative payloads. Selection applies to both components.

A lookup in TorchBatchFieldDerivativeCollection returns this payload for a complex input.

real

Packed gradient of the real output component by original batch index.

Type:

TorchBatchFieldDerivativePayload

imag

Packed gradient of the imaginary output component, or None when the field output is real.

Type:

TorchBatchFieldDerivativePayload | None

select(index=None)[source]

Select the same field position from both output components.

Parameters:

index (int | None, optional) – Field position. None selects all positions.

Returns:

Complex derivative payload with both components selected.

Return type:

TorchBatchComplexFieldDerivativePayload

property derivatives

Return nested derivatives for both output components.