cosmiq#

cosmiq: hybrid quantum-classical algorithms on neutral atoms, CPUs and GPUs.

AnalogProgram

Subclass it and implement drive.

Bounded

A value kept inside [low, high].

CapabilityError

The target can't represent what was asked (trap layouts, atom loss, ...).

Channel

One channel.

ChannelData

One channel of a schedule.

ConstraintError

A program breaks one or more rules of its target device.

CosmiqDeprecationWarning

A public cosmiq name that will be removed in a later release.

CosmiqError

Base class of every error cosmiq raises on purpose.

Drive

Everything a program drives.

Emulator

A state-vector emulator of the device a schedule targets (see the Emulator guide).

FormatError

A document or value that isn't valid cosmiq input (bad JSON, wrong shape, NaN).

GlobalDrive

The global Rydberg drive.

LocalDetuning

The local detuning map: a fixed weight \(c_i \in [0, 1]\) per atom, and one PWL waveform \(\delta(t) \le 0\) shared by all, entering as \(-c_i \delta(t)\, n_i\).

Register

N atoms in 2D, in a fixed order (atom 0 first), with labels "q0", "q1", ...

Samples

A schedule on a uniform grid of step dt (µs).

Schedule

A program evaluated to numbers.

ScheduleData

A schedule as numbers: µm, µs, rad/µs, rad.

UnverifiedWarning

A call through Emulator(..., unverified="reason") bypassed at least one refusal: no accuracy claim applies to its result.

Violation

One broken device rule, with everything needed to understand and fix it.

Waveform

kind="pwl": values at the K times, linear in between.

bounded

A Bounded value: `self.omega = cq.bounded(1.5 * MHz, low=0.0, high="device", field="analog.rydberg_global.amplitude.max"), thenself.omega()` in drive().

constant

pwl([0, duration], [value, value]).

pad_to

Extend to end at t: pwl appends (t, value or the last value); pwc extends the last segment, or adds one when value is given.

program

The functional form: drive_fn(params, *inputs), where params is the program's nn.ParameterDict built from parameters (floats become float64 nn.Parameters).

project_

Put every clamp-mode bounded value in module back inside its limits, in place and under no_grad: the projection of projected gradient descent.

pwc

Piecewise-constant: values[k] on [edges[k], edges[k + 1]).

pwl

Piecewise-linear through (times[k], values[k]).

sample

Raises FormatError unless the duration and every breakpoint (and PWC edge) are whole numbers of dt (within 1e-9 µs): a cell can't hold a breakpoint inside it, so a ramp that starts or ends there would be sampled wrong.

sampled

Piecewise-linear through samples at t_k = k * dt (so it counts as PWL for R16).

__version__

Classes

class cosmiq.AnalogProgram(register: Register)#

Bases: Module

Subclass it and implement drive. Parameters are ordinary nn.Parameters.

property register: Register#
property target: DeviceSpec | None#

The device the program is targeted at, or None. (Not a torch.device: the parameters’ torch device is where program.to(...) put them.)

property report: DiscretizationReport | None#

Every rounding behind the last schedule a targeted evaluation returned (a forward, or to_target’s trial run); None before the first one.

drive(*inputs: Any) → Drive | GlobalDrive#

Plain Python, run on every forward, so breakpoints work inside it.

forward(*inputs: Any) → Schedule#

drive(*inputs), evaluated into a Schedule; when targeted, discretised and checked (ConstraintError, naming the parameters behind each bad value).

to_target(device: str | DeviceSpec, *, strict: bool = False) → Self#

Bind a device and check what’s fixed now: the register (R1-R3, R5) and, when drive() takes no inputs, a trial forward. Resolves bounded(..., "device") limits. Raises ConstraintError or CapabilityError, and FormatError for a device id that isn’t bundled (naming the ones that are). Returns self.

The register is checked as the device will see it: rounded onto its position grid first, so an off-grid position is fine when its rounded place is (R3 is checked after rounding; atoms that rounding brings together raise R3). On any error the program is left as it was (its target, and its Bounded values).

class cosmiq.Bounded(init: float, *, low: float | Literal['device'] | None = None, high: float | Literal['device'] | None = None, field: str | None = None, mode: Literal['sigmoid', 'clamp'] = 'sigmoid')#

Bases: Module

A value kept inside [low, high]. Call it to get the value: self.omega().

The trainable parameter is raw, and mode says how it maps to the value:

  • “sigmoid” (the default): \(\mathrm{value}=\mathrm{low}+(\mathrm{high}-\mathrm{low})\cdot\mathrm{sigmoid}(\mathrm{raw})\). With only one limit, a softplus keeps the value on its side: \(\mathrm{low} + \mathrm{softplus}(\mathrm{raw})\), or \(\mathrm{high} - \mathrm{softplus}(\mathrm{raw})\). Every raw is inside, so any optimiser works unchanged, but the limits are only approached: the gradient vanishes there. init must lie strictly inside the limits.

  • “clamp”: raw is the value, and the limits are closed: init may sit on one. After each optimiser step, project it back inside with cq.project_(program), or let cq.project_(program, after=optimizer) do it after every optimizer.step(). A value left outside raises FormatError when it’s called. Use it when the optimum may lie on a limit, full \(\Omega\) for example. With an optimum at cosmiq-ref-1’s \(\Omega\) maximum (15.079 rad/µs on its grid), Adam (lr 0.25) reached it exactly in clamp mode, at step 29 of 60, while the sigmoid was still 0.045 rad/µs short at step 60 (tests/test_program.py).

A “device” limit is read from the target’s spec at field when the program is targeted, and moved onto the device’s grid (see resolve); until then calling the value raises FormatError. Retargeting keeps the current value, if the new limits allow it. The limits and the mode are saved in state_dict with raw.

forward() → Tensor#
resolve(spec: DeviceSpec) → None#

Replace “device” limits with the spec’s value at field (e.g. “analog.rydberg_global.amplitude.max”). Called by to_target.

The limit is moved onto the device’s grid, the multiples of its section’s resolution: a maximum to the largest grid value inside it, a minimum to the smallest. So rounding a value inside the limits can’t push it outside them (15.079644… with resolution 1e-3 becomes 15.079). field may also name a section with min and max (for example “analog.rydberg_global.detuning”), which is how both limits come from the device.

state() → tuple[float | None, float | None, bool, Tensor]#

Everything resolve() changes, for to_target to put back on failure.

restore(state: tuple[float | None, float | None, bool, Tensor]) → None#
project_() → None#

Clamp mode: put the value back inside its known limits, in place. A no-op in sigmoid mode, where every raw is inside.

class cosmiq.CapabilityError#

Bases: CosmiqError

The target can’t represent what was asked (trap layouts, atom loss, …).

class cosmiq.Channel(name: Literal['amplitude', 'detuning', 'phase', 'local_detuning'], kind: Literal['pwl', 'pwc'], times: tuple[float, ...], values: Tensor, free: tuple[bool, ...])#

Bases: object

One channel. pwl: K times; pwc: K + 1 edges. values is float64 [B, K].

name: Literal['amplitude', 'detuning', 'phase', 'local_detuning']#
kind: Literal['pwl', 'pwc']#
times: tuple[float, ...]#
values: Tensor#
free: tuple[bool, ...]#
class cosmiq.ChannelData(name: Literal['amplitude', 'detuning', 'phase', 'local_detuning'], kind: Literal['pwl', 'pwc'], times: tuple[float, ...], values: NDArray[float64], free: tuple[bool, ...])#

Bases: object

One channel of a schedule.

  • kind="pwl": times has K breakpoints, values is [B, K], linear in between.

  • kind="pwc": times has K + 1 segment edges, values is [B, K], constant per segment.

  • free[k] is True where value k depends on parameters or inputs (a slot on the wire), False where it’s a fixed number.

name: Literal['amplitude', 'detuning', 'phase', 'local_detuning']#
kind: Literal['pwl', 'pwc']#
times: tuple[float, ...]#
values: NDArray[float64]#
free: tuple[bool, ...]#
class cosmiq.ConstraintError(violations: list[Violation] = <factory>)#

Bases: CosmiqError

A program breaks one or more rules of its target device. Carries all of them.

violations: list[Violation]#
class cosmiq.CosmiqDeprecationWarning#

Bases: FutureWarning

A public cosmiq name that will be removed in a later release.

A FutureWarning rather than a DeprecationWarning, so users see it by default and not only their test runners.

class cosmiq.CosmiqError#

Bases: Exception

Base class of every error cosmiq raises on purpose.

class cosmiq.Drive(global_drive: GlobalDrive, local_detuning: LocalDetuning | None = None)#

Bases: object

Everything a program drives. AnalogProgram.drive may return this or a GlobalDrive.

global_drive: GlobalDrive#
local_detuning: LocalDetuning | None = None#
class cosmiq.Emulator(device: device | str | None = None, precision: Literal['auto', 'single', 'double'] = 'auto', method: Literal['auto', 'split', 'krylov', 'dense', 'density_matrix'] = 'auto', backend: Literal['auto', 'torch-ref', 'torch-kron', 'triton'] = 'auto', gradient: Literal['auto', 'adjoint', 'checkpoint', 'none', 'trajectory'] = 'auto', tol: float | None = None, samples_only: bool = False, observable: Observable | None = None, max_memory: int | None = None, space: Literal['full', 'blockade', 'tensor'] = 'full', blockade: Literal['kings'] | None = None, unverified: str | None = None, bond_dim: int | None = None)#

Bases: Module

A state-vector emulator of the device a schedule targets (see the Emulator guide).

emu = cq.Emulator()                      # CPU, complex128
result = emu.run(program(), observables=[density()])
result.expectations["density"]           # [B, N], differentiable
  • device: the torch device, or None for the schedule’s own (“mps” is refused);

  • precision, method, backend, gradient, tol, max_memory: the engine’s options (EngineOptions); “auto” picks, and the report says what;

  • samples_only: shots only, read as the analog hardware would (a lost atom reads 1);

  • observable: what forward returns, so nn.Sequential(program, emulator) works;

  • space: “full” (the \(2^N\) state space) or “blockade”, the blockade fast mode: allowed only on the registers, programs and observables that were tested (see Claims and limits), everything else refused; blockade="kings" blockades the diagonals of a square lattice; or “tensor”, an MPS run by two-site TDVP, allowed only on the chains, programs and sizes that were tested, everything else refused.

  • bond_dim: space=”tensor“‘s bond dimension: None (the cell’s tested \(\chi\)), or that \(\chi\), 32 at \(N \le 12\) and 64 at \(N = 16\) (the tested values).

  • unverified: None, or the reason you run past refusals for lack of evidence (see “Running outside the tested range” in the Emulator guide): an untested or failed cell then warns (cq.UnverifiedWarning) and runs, and its report says verified=False. In space="blockade", the cells outside its table; in the full space, the density matrix above 12 atoms (its gradient above 10), the trajectory gradient above 6 atoms or in complex64, and either off the CPU. Hard refusals stay hard, and remote sessions, cq.remote.local(), PennyLane and cq.gradients.estimate refuse such an emulator. Read-only; logged at WARNING when built and when unpickled. No accuracy claim of any kind applies to a result that bypassed a refusal.

last_report is the report of this emulator’s last successful call (run, forward or vjp), None before one or after a refused call. Shared across threads, the last writer wins.

property unverified: str | None#

The reason given to unverified=, or None: read-only.

property last_report: EmulationReport | None#

The report of this emulator’s last successful run, forward or vjp; None before one, and after a refused or failed call. Shared across threads, the last writer wins.

forward(schedule: Schedule) → Tensor#

The value of observable (set in the constructor), [B, …]: for nn.Sequential(program, emulator).

run(schedule: Schedule | ScheduleData, *, observables: Sequence[Observable] = (), shots: int | None = None, noise: Literal['device', 'hardware'] | NoiseModel | None = None, trajectories: int | None = None, seed: int | None = None, spec: DeviceSpec | None = None, dt: float | None = None, keep_state: bool = False, initial: Tensor | None = None) → EmulationResult#

Evolve every batch row of schedule and measure it.

  • schedule: a targeted Schedule (a program’s output), any schedule with spec=, or a loaded ScheduleData (no gradients: use vjp). The device’s C6, clock and calibration come from its target, or from spec.

  • dt: the cell length in µs; the device clock by default. Every breakpoint must be on its grid.

  • observables: what to measure, in expectation (exact over K trajectories).

  • shots: sample this many per row (shot mode).

  • noise: None (ideal), “device” (every noise source in the calibration, except the three “hardware” adds), “hardware” (“device” plus T2 by quantum jumps, the ramp filter and loss during the sequence: forward only, on split), or a NoiseModel.

  • trajectories: K. Expectation mode: 100 by default. Shot mode: one per shot up to 1,000, then shots spread over them. One whenever the noise draws nothing per trajectory.

  • seed: the root of every draw; None draws one from torch’s generator, and the report records it.

  • keep_state: keep \(\psi(T)\) in the result (noiseless runs only; not under method="density_matrix").

  • initial: start from this state instead of \(|g\ldots g\rangle\) (noiseless runs only): complex, \([2^N]\) for every row or \([B, 2^N]\), in CONVENTIONS.state_order, each row of norm 1. Gradients flow back to it, so runs and gates chain into one torch graph.

Through an Emulator(..., unverified=...), a call that bypasses a refusal warns (cq.UnverifiedWarning) and reports verified=False.

vjp(data: ScheduleData, observables: Sequence[Observable], cotangents: Mapping[str, Any], *, noise: Literal['device', 'hardware'] | NoiseModel | None = None, trajectories: int | None = None, seed: int | None = None, spec: DeviceSpec | None = None, dt: float | None = None) → Tensor#

\(\partial L/\partial\,\mathrm{slots}\), [B, n_slots] float64 on the CPU, for \(L = \sum_\mathrm{name} \sum \mathrm{cotangent} \cdot \mathrm{value}\) over observables: the server side of a gradient. The client multiplies it by its document’s Jacobian (\(\partial\,\mathrm{slots}/\partial\,\mathrm{parameters}\)) to get its parameters’ gradient.

data is a loaded document’s ScheduleData; its slots (the free values, in wire order) become leaf tensors. cotangents has one [B, …] array per observable, by name, shaped like its value.

Through an Emulator(..., unverified=...), a call that bypasses a refusal warns (cq.UnverifiedWarning) and reports verified=False in last_report.

class cosmiq.FormatError#

Bases: CosmiqError, ValueError

A document or value that isn’t valid cosmiq input (bad JSON, wrong shape, NaN).

class cosmiq.GlobalDrive(amplitude: Waveform, detuning: Waveform, phase: Waveform | float | Tensor = 0.0)#

Bases: object

The global Rydberg drive. \(\Omega\) (amplitude) and \(\Delta\) (detuning) are PWL, \(\varphi\) (phase) is PWC or a constant. \(\Omega \ge 0\) and the other device limits are checked when the program is targeted.

A phase built with cq.constant (two breakpoints, one value) is a constant, so it is stored as the equivalent one-segment PWC waveform.

amplitude: Waveform#
detuning: Waveform#
phase: Waveform | float | Tensor = 0.0#
class cosmiq.LocalDetuning(weights: Sequence[float], detuning: Waveform)#

Bases: object

The local detuning map: a fixed weight \(c_i \in [0, 1]\) per atom, and one PWL waveform \(\delta(t) \le 0\) shared by all, entering as \(-c_i \delta(t)\, n_i\).

The weights’ range \([0, 1]\) and \(\delta \le 0\) are device rules (R18), checked when the program is targeted; here they need only be fixed, finite numbers, one per atom.

weights: Sequence[float]#
detuning: Waveform#
class cosmiq.Register(positions: Sequence[Sequence[float]] | NDArray[floating[Any]] | Tensor, labels: Sequence[str] | None = None)#

Bases: object

N atoms in 2D, in a fixed order (atom 0 first), with labels “q0”, “q1”, …

classmethod chain(n: int, spacing: float, *, center: bool = True) → Register#

n atoms on the x axis, spacing µm apart.

classmethod square(side: int, spacing: float, *, center: bool = True) → Register#

side by side atoms on a square grid, row by row.

classmethod rectangular(rows: int, cols: int, spacing: float, *, center: bool = True) → Register#

rows by cols atoms on a square grid, row by row (\(\text{atom index} = \text{row} \cdot \text{cols} + \text{col}\)).

classmethod triangular(rows: int, cols: int, spacing: float, *, center: bool = True) → Register#

rows of cols atoms, nearest neighbours spacing apart; odd rows are shifted by half a spacing. Row by row, like rectangular.

classmethod from_coordinates(coordinates: Sequence[Sequence[float]] | NDArray[floating[Any]] | Tensor, labels: Sequence[str] | None = None) → Register#

Atoms at these absolute (x, y) positions, in µm. Nothing is moved.

property positions: NDArray[float64]#

A read-only [N, 2] float64 copy, µm.

property labels: tuple[str, ...]#
__len__() → int#
distances() → NDArray[float64]#

[N, N] pairwise distances, µm.

translated(dx: float, dy: float) → Register#

The same atoms, moved by (dx, dy) µm, with the same labels.

to_dict() → dict[str, Any]#

{“positions”: [[x, y], …] in µm, “labels”: […]}: plain JSON-ready values.

classmethod from_dict(data: dict[str, Any]) → Register#

The inverse of to_dict. Unknown keys raise FormatError: they would be ignored physics.

class cosmiq.Samples(dt: float, t: Tensor, amplitude: Tensor, detuning: Tensor, phase: Tensor, local_detuning: Tensor | None, local_weights: Tensor | None)#

Bases: object

A schedule on a uniform grid of step dt (µs). t holds the n_t segment midpoints; each channel is [B, n_t]; PWL channels are sampled at the midpoints, PWC exactly.

dt: float#
t: Tensor#
amplitude: Tensor#
detuning: Tensor#
phase: Tensor#
local_detuning: Tensor | None#
local_weights: Tensor | None#
class cosmiq.Schedule(register: Register, channels: Mapping[Literal['amplitude', 'detuning', 'phase', 'local_detuning'], Channel], local_weights: tuple[float, ...] | None, device: str | None, batch_size: int, capabilities_version: str | None = None)#

Bases: object

A program evaluated to numbers. The “amplitude”, “detuning” and “phase” channels are always present; “local_detuning” is there exactly when local_weights is not None.

channels is a read-only mapping. The exporters and formats check a schedule’s structure, but not its device limits again: they trust that a targeted forward() checked them. So don’t change its tensors in place. For new values, evaluate the program again, or build a schedule with from_data and check it with cosmiq.devices.check.

Schedules compare by identity: their values are tensors, which have no single truth value. Compare to_data() arrays, or channel values with torch.equal.

register: Register#
channels: Mapping[Literal['amplitude', 'detuning', 'phase', 'local_detuning'], Channel]#
local_weights: tuple[float, ...] | None#
device: str | None#
batch_size: int#
capabilities_version: str | None = None#

The capabilities version of device the schedule was checked against: kept from a document by from_data (and to_data writes it back), set to the target’s by discretisation, which checks against it; None for a schedule nothing checked yet (from_drive), for which formats.dumps writes the bundled device’s own version.

classmethod from_drive(register: Register, drive: Drive | GlobalDrive, *, device: str | None = None) → Schedule#

Evaluate a Drive: float64, a common batch size, structural checks (R15 channels end together, R16, RF). Raises FormatError; device limits are not checked here.

A GlobalDrive is accepted too. A phase given as one value becomes one PWC segment over the whole schedule. Channels with batch size 1 broadcast to the others’. Ends that differ only by float noise (at most 1e-9 µs) are made exactly equal.

property duration: float#

The end time in µs, shared by every channel (R15).

to_data() → ScheduleData#

Detached numpy copies, for the check, formats and exporters.

classmethod from_data(data: ScheduleData) → Schedule#

Back to tensors (no gradients), e.g. after formats.loads.

Runs the same structural checks as from_drive (RD, RF, RT, R15, R16, shapes; cosmiq._structure) and raises FormatError, so every Schedule keeps the same invariants. The device label and its capabilities version are kept as they are.

sample(dt: float | None = None, rule: Literal['midpoint'] = 'midpoint') → Samples#

See sample.

class cosmiq.ScheduleData(positions: NDArray[float64], labels: tuple[str, ...], channels: dict[Literal['amplitude', 'detuning', 'phase', 'local_detuning'], ChannelData], local_weights: NDArray[float64] | None, device: str | None, batch_size: int, capabilities_version: str | None = None)#

Bases: object

A schedule as numbers: µm, µs, rad/µs, rad. Compares by identity (its fields are arrays).

channels always has “amplitude”, “detuning” and “phase”; “local_detuning” is present exactly when local_weights is not None.

positions: NDArray[float64]#
labels: tuple[str, ...]#
channels: dict[Literal['amplitude', 'detuning', 'phase', 'local_detuning'], ChannelData]#
local_weights: NDArray[float64] | None#
device: str | None#
batch_size: int#
capabilities_version: str | None = None#

The device’s capabilities version the schedule was checked against, as a document recorded it (formats.loads keeps it, so a round trip keeps the digest); None when it isn’t known, and formats.dumps then writes the bundled device’s own version.

property duration: float#

The schedule’s end time in µs (every channel ends there, R15).

class cosmiq.UnverifiedWarning(message: str = '', *, hits: Sequence[Hit] = (), reason: str = '', site: str = '')#

Bases: UserWarning

A call through Emulator(..., unverified="reason") bypassed at least one refusal: no accuracy claim applies to its result.

  • codes, refusals, hits: what it bypassed;

  • reason: the emulator’s unverified;

  • site: “file:line” where the emulator was built.

class cosmiq.Violation(rule: str, message: str, device: str | None = None, field: str | None = None, channel: str | None = None, t_start: float | None = None, t_end: float | None = None, atoms: tuple[int, ...] = (), index: int | None = None, batch_index: int | None = None, value: float | None = None, limit: float | None = None, unit: str | None = None, caused_by_rounding: bool = False, envelope: Literal['target', 'strict'] = 'target', parameters: tuple[str, ...] = (), fix: str | None = None)#

Bases: object

One broken device rule, with everything needed to understand and fix it.

Values and limits are in cosmiq’s units (µs, µm, rad/µs, rad, \(\mathrm{rad/\mu s^2}\)), named by unit.

rule: str#

The rule id: “R6”, “R13”, “RF”, …

message: str#

One line saying what’s wrong.

device: str | None = None#

The device and its capabilities version, “cosmiq-ref-1@1.0.0”.

field: str | None = None#

The device-spec field that sets the limit, “analog.rydberg_global.amplitude.max”.

channel: str | None = None#

“amplitude”, “detuning”, “phase”, “local_detuning”, or None for register rules.

t_start: float | None = None#
t_end: float | None = None#

The time window, in µs.

atoms: tuple[int, ...] = ()#

The atoms involved (register rules).

index: int | None = None#

The breakpoint (pwl) or segment (pwc) index within channel, for value rules.

batch_index: int | None = None#
value: float | None = None#
limit: float | None = None#
unit: str | None = None#
caused_by_rounding: bool = False#

True when the value only broke the rule after discretisation.

envelope: Literal['target', 'strict'] = 'target'#

Which limits rejected it: the target device’s, or the strict envelope’s.

parameters: tuple[str, ...] = ()#

The nn.Parameter (or input) names the value depends on, when known.

fix: str | None = None#

A hint for fixing it.

class cosmiq.Waveform(kind: Literal['pwl', 'pwc'], times: tuple[float, ...], values: tuple[float | Tensor, ...])#

Bases: object

kind="pwl": values at the K times, linear in between. kind="pwc": times are K + 1 segment edges, one value per segment.

kind: Literal['pwl', 'pwc']#
times: tuple[float, ...]#
values: tuple[float | Tensor, ...]#
property duration: float#
property free: tuple[bool, ...]#

True for each value that is a tensor (depends on parameters or inputs).

tensor(*, dtype: dtype = torch.float64, device: device | None = None) → Tensor#

The values as one [B, K] tensor, \(B \ge 1\), differentiable. Floats broadcast; tensors of different batch sizes raise FormatError.

Functions

cosmiq.bounded(init: float, *, low: float | Literal['device'] | None = None, high: float | Literal['device'] | None = None, field: str | None = None, mode: Literal['sigmoid', 'clamp'] = 'sigmoid') → Bounded#

A Bounded value: `self.omega = cq.bounded(1.5 * MHz, low=0.0, high=”device”, field=”analog.rydberg_global.amplitude.max”), thenself.omega()` in drive(). mode="clamp" stores the value itself, for an optimum on a limit (see Bounded).

cosmiq.constant(duration: float, value: float | Tensor) → Waveform#

pwl([0, duration], [value, value]).

cosmiq.pad_to(waveform: Waveform, t: float, value: float | Tensor | None = None) → Waveform#

Extend to end at t: pwl appends (t, value or the last value); pwc extends the last segment, or adds one when value is given. The explicit fix for R15.

t equal to the current end returns the waveform unchanged when no value is given.

cosmiq.program(register: Register, drive_fn: Callable[[...], Drive | GlobalDrive], parameters: Mapping[str, float | Tensor] | None = None) → AnalogProgram#

The functional form: drive_fn(params, *inputs), where params is the program’s nn.ParameterDict built from parameters (floats become float64 nn.Parameters).

The dict is registered as params, so parameters are named “params.<key>” in named_parameters(), in violations and for functional_call. An nn.Parameter passed in is used as is; another tensor becomes a new nn.Parameter with its values.

cosmiq.project_(module: Module, *, after: None = None) → None#
cosmiq.project_(module: Module, *, after: Optimizer) → RemovableHandle

Put every clamp-mode bounded value in module back inside its limits, in place and under no_grad: the projection of projected gradient descent. Call it after each step of an optimiser that isn’t torch’s (autograd’s, PennyLane’s).

With after=optimizer, it also projects after every optimizer.step() from now on, by a step post-hook (Optimizer.register_step_post_hook), and returns the hook’s handle: handle.remove() stops it.

optimizer = torch.optim.Adam(program.parameters(), lr=0.05)
cq.project_(program, after=optimizer)

Sigmoid-mode values are left alone: they can’t leave their limits.

cosmiq.pwc(edges: Sequence[float], values: Sequence[float | Tensor] | Tensor) → Waveform#

Piecewise-constant: values[k] on [edges[k], edges[k + 1]). values may also be one tensor, as for pwl.

cosmiq.pwl(times: Sequence[float], values: Sequence[float | Tensor] | Tensor) → Waveform#

Piecewise-linear through (times[k], values[k]). Raises FormatError on RT/RF/shape.

values may also be one tensor: [K] (K scalars) or [B, K] (K batched values).

cosmiq.sample(schedule: Schedule, dt: float | None = None, rule: Literal['midpoint'] = 'midpoint') → Samples#

Raises FormatError unless the duration and every breakpoint (and PWC edge) are whole numbers of dt (within 1e-9 µs): a cell can’t hold a breakpoint inside it, so a ramp that starts or ends there would be sampled wrong. The error names the first breakpoint off the grid.

dt=None means the clock period of the schedule’s device, a bundled device looked up by id; an untargeted schedule needs an explicit dt.

Cell \(j\) covers \([j \cdot dt, (j + 1) \cdot dt)\) and is represented by its midpoint \(t_j = (j + \tfrac{1}{2}) \cdot dt\). A PWL channel is evaluated there by linear interpolation, which is its exact average over the cell when the breakpoints are on the grid. A PWC channel takes the value of the segment that contains \(t_j\): exactly the segment’s value, never a blend. Differentiable in the channel values.

cosmiq.sampled(dt: float, samples: Sequence[float | Tensor] | Tensor) → Waveform#

Piecewise-linear through samples at t_k = k * dt (so it counts as PWL for R16).

samples may be a [K] tensor, or [B, K] for a batch.

Values

cosmiq.__version__ = '0.1.0'#