API Overview¶
CASCAQit exposes a compact root API for common user workflows and package-level APIs for explicit ownership.
Prefer root imports for examples and quickstarts. Prefer package-level imports when writing larger applications, tests, or integration code where ownership boundaries should remain visible.
The pages below describe the SDK’s public interfaces. Use documentation that matches your installed SDK, and consult each interface’s parameters, return values and examples.
Related user docs: Quickstart, First Programs, Tutorials, QAOA And VQE, Unified Problem Compiler, Retry And Resume, Examples Guide, Standard Experiment Visualization, and Limitations.
The usual reading order is examples/learning/ for the first pass, examples/user/ for fuller tutorial flows, and examples/release/ only for short package checks.
The package root contains 59 frequent-workflow exports. docs/reference/public_api_manifest.json is the machine-readable allowlist.
| Area | Root exports |
|---|---|
| Programs and controls | AHSProgram, AtomRegister, Circuit, HybridProgram, SiteMask, SitePattern, VanDerWaalsInteraction, Waveform |
| Local execution | LocalAhsSimulator, LocalDigitalSimulator, LocalBackend, SimulationOptions, RetryPolicy, MockNeutralAtomTarget |
| Parameters and noise | Parameter, ParameterManager, ParameterScan, NoiseChannel, NoiseModel |
| Observables | Observable, ObservableSet, PauliI, PauliProduct, PauliX, PauliY, PauliZ, PauliZZ |
| Problems and algorithms | GraphProblemIR, QUBOProblemIR, IsingModelIR, HamiltonianTerm, PauliHamiltonian, PauliMeasurementConfig, ReadoutCalibration, ReadoutMitigationConfig, SampledSelectionConfig, OptimizerConfig, SPSAConfig, SPSALearningRateCalibrationConfig, SPSAStoppingConfig, SPSAIterationIR, AdamConfig, AdamStoppingConfig, AdamIterationIR, QAOA, VQE, VariationalResult, VQESamplingBenchmarkConfig, VQESamplingBenchmarkResult, VQEStabilityConfig, VQEStabilityDiagnosticResult |
| Results and reports | ResultIR, build_result_view, build_counts_histogram, visualize |
| Errors | CASCAQitError, ProgramValidationError, CapabilityError, BackendExecutionError |
Analog¶
from cascaqit import AHSProgram, AtomRegister, SiteMask, SitePattern
from cascaqit import VanDerWaalsInteraction, Waveform
from cascaqit import LocalAhsSimulator, MockNeutralAtomTarget
Use these APIs to build atom registers, define waveforms, validate programs, and run local analog simulations.
Primary objects: AHSProgram, AtomRegister, SitePattern, VanDerWaalsInteraction, Waveform, LocalAhsSimulator, and MockNeutralAtomTarget.
VanDerWaalsInteraction(c6=..., cutoff_radius=..., enabled=...) declares the following static coherent term on AHSProgram:
c6 uses rad*um^6/us, coordinates and the cutoff use um, and a pair is included when distance <= cutoff_radius. enabled=False preserves the declared configuration and identity but contributes no pair energy. Positive and negative C6 are supported. The same Euclidean geometry path handles arbitrary two-dimensional coordinates; a one-dimensional register is its collinear special case.
The interaction lowers to canonical Native IR and is executed by standalone Analog, Hybrid, exact density-matrix, and trajectory simulation. It is a deterministic coherent term owned by the crosstalk channel with the number_number operator; it is distinct from the optional coherent XX noise channel, which has its own noise report. See examples/user/van_der_waals_interaction.py for a complete offline run.
AHSProgram.parameter() returns a unit-aware declaration value. Constant, linear, piecewise, and shape-preserving PCHIP Waveform.interpolated() waveforms accept those values and safe expressions; Waveform.concat() composes compatible non-interpolated serial segments. Call bind() before lowering typed declarations, then use validate(), ValidatedAHSProgram.discretize(), or run() for the local path. The resulting ProgramIR contains only numeric waveform values and site-pattern weights. See Interpolated Waveforms.
AHSProgram.local_detuning() appends an experimental local-simulator term. Repeated calls create ordered additive terms. Each SitePattern must name every filled register site exactly once; numeric or canonical dimensionless parameter weights bind to numeric IR in filled-register order. SiteMask.constant() provides static sparse binary addressing, while SiteMask.piecewise() changes the active sites at declared frame times. Both lower to canonical dense SiteAddressingIR. See Local Detuning for the executable path and limits.
AHSProgram.local_rabi() appends an experimental site-addressed Rabi amplitude with a shared numeric or waveform phase. Repeated calls create ordered coherent terms. Canonical amplitude, phase, weighted pattern parameters, and constant/piecewise binary masks flow through target validation, discretization, ideal/density/trajectory execution, pulse visualization, resource evidence, and offline compile. See Local Rabi Control.
AtomRegister supports line, square, rectangular, triangular, and custom geometry. Immutable with_site_status() transitions preserve filled, vacant, defect, and loading-failed layout facts; only filled target sites enter the logical state order. cascaqit.analog.SitePhasePattern adds bound per-site radian offsets to local Rabi. The local Target projects typed control schedules and checks concurrency, mutual exclusion, bandwidth, slew, and crosstalk policy. See Experiment Control And Register Lifecycle.
CompilerPipeline.compile() accepts discretized local-detuning and local-Rabi ProgramIR only when the explicit target snapshot projects the required patterned channels. Its ReferenceCompiledProgramIR is a public offline reference contract, not an ExecutionPackage, private compiler output, or hardware payload.
Optional Pulser Reference¶
from cascaqit.simulators import PulserReferenceBackend, PulserReferenceJob
from cascaqit.simulators.pulser_reference import (
PulserReferenceAdapter,
compare_pulser_reference,
)
PulserReferenceBackend gives the frozen one-site global Analog subset the same lazy Job shape as LocalBackend; both return standard ResultIR. reference_run() exposes the existing typed Pulser evidence for state-fidelity comparison. Install .[reference-pulser] for actual execution. Unsupported semantics, missing dependencies, sampling, and seed inputs fail before solver execution; default imports never import the Pulser runtime packages.
Digital¶
from cascaqit import Circuit
Use this fluent API to build small digital gate programs, run local simulation, and inspect bit-order and measurement evidence. Advanced users can still import the native IR types from cascaqit.digital.
Circuit.parameter() and safe expressions remain in the declaration layer until explicit bind(). Reusable circuits support append(), complete qubit-mapped compose(), inverse(), bounded repeat(), and capability-bounded controlled(). Only a fully bound Circuit lowers to the existing float-only DigitalProgramIR.
Primary object: Circuit. Advanced parameter value types are owned by cascaqit.digital and are not root exports. See Digital Circuit Walkthrough.
Hybrid Syntax¶
from cascaqit.syntax import digital_block, analog_block, measurement_block
from cascaqit.syntax import program_syntax, analyze
The experimental package-level frontend declares blocks and lowers Python syntax to ProgramSyntaxAST and SemanticProgramHIR. Decorators inspect signatures by default; lower_body=True additionally captures a restricted declaration body that BlockDefinition.lower() can materialize as a native Circuit/AHSProgram without executing the function.
HybridProgram is the semantic orchestration model for the analyzed blocks:
from cascaqit import HybridProgram
program = HybridProgram.from_hir(analysis.hir)
Hybrid Parameters¶
from cascaqit import Parameter, ParameterManager, ParameterScan
The canonical parameter package supports typed declarations, defaults, bounded arithmetic expressions, automatic Digital / Analog targets, and deterministic scans. HybridProgram.parameters exposes the collected ParameterManager view.
Local Hybrid Simulation¶
from cascaqit import HybridProgram, LocalBackend, SimulationOptions
from cascaqit import NoiseChannel, NoiseModel
from cascaqit.simulators import LocalHybridExecutionBuilder
from cascaqit.simulators import LocalHybridScanJob, LocalHybridScanJobResult
Build typed payloads with HybridProgram.digital()/analog()/measure_all(). LocalBackend.run(program), run(program, params=...), and run(program, sweep=...) cover static, single-bind, and scan execution. Payload snapshots, parameter targets, compile preflight, and terminal measurement binding are automatic.
Pass options=SimulationOptions(...) to control the state method, integrator, dtype, CPU device, memory budget, workers, trajectories, tolerances, maximum accepted steps, and seed. Planning is resource-driven and happens before Job creation. Analog/Hybrid state-vector, subspace, and density paths support segmented DOP853 adaptive integration; trajectory remains fixed-step. Use result.execution_config() for the executed selection, result.solver_evidence() for actual numerical work, result.state_transitions() for the canonical state/time chain, and result.resource_usage() for typed resource observations. Executable NoiseModel inputs select exact density-matrix evolution or batched trajectories. The eight canonical channels cover preparation, dephasing, gate, idle, crosstalk, Hybrid boundary, atom loss, and readout noise. sweep and noise can be combined for resource-bounded noisy scans.
The simple and advanced APIs share one implementation. HybridProgram.analyze(), compile(), parameters, execution_builder(), and to_ir() remain available on the same object. HybridProgramIR, LocalExecutionPlan, HybridBlockSimulator, and LocalHybridExecutionBuilder remain advanced owner-package APIs; IR and plans are not direct Backend inputs. See Local Hybrid Simulation.
Persistent Local Jobs¶
from cascaqit import LocalBackend, RetryPolicy
With LocalBackend(store=...), use run(..., retry=RetryPolicy(...)), resume(job_id), and history(...) for local durable execution. Detailed history and attempt contracts remain package imports from cascaqit.backends. See Retry, Resume, And Local History.
QAOA And VQE¶
from cascaqit import OptimizerConfig, QAOA, VQE
from cascaqit import HamiltonianTerm, PauliHamiltonian, VariationalResult
QAOA(...).run() and VQE(...).run() provide the common problem/operator-to-report path. QAOA accepts MIS, MWIS, QUBO, and Ising inputs; VQE accepts QUBO, Ising, and typed weighted Pauli Hamiltonians. Both use canonical Circuit parameters, one LocalBackend Job and Observable batch per objective evaluation, deterministic multi-start optimization, a separate final sampling Job, and the same immutable VariationalResult evidence. SciPy owns COBYLA, Nelder-Mead, Powell, and L-BFGS-B; CASCAQit owns the native SPSA and Adam loops. VQE accepts HardwareEfficientAnsatz, CardinalityPreservingAnsatz, or a parameterized custom Circuit. Fixed-cardinality results retain per-group weight distributions, preservation rates, and sampled violation counts in cardinality_subspace.
OptimizerConfig(method="SPSA", spsa=SPSAConfig(...)) uses directions_per_iteration=1 by default and accepts multiple complete plus/minus directions per iteration. SPSADirectionIR in cascaqit.algorithms records each Rademacher direction, parameters, pooled objectives, and direction gradient. Root-exported SPSAIterationIR records their averaged gradient, the component standard error for two or more directions, gain schedule, projected update, update norm, and evaluation offsets. Exact objectives use one Backend Job per parameter point. Digital VQE may instead use finite-shot QWC measurement with fixed or bounded standard-error-driven repeats under ideal execution or a canonical NoiseModel; sampled noise supports Digital preparation, gate, idle, crosstalk, and readout channels with auto, density_matrix, or trajectory simulation. ReadoutCalibration and ReadoutMitigationConfig add explicit tensor-product linear-inverse mitigation to the sampled estimator while preserving raw counts. VQE.benchmark_sampling() compares ideal exact, single-sample, fixed-repeat, and adaptive-repeat strategies with paired initial points and seeds, then performs an independent exact check at every sampled-selected binding.
Set SPSAConfig(learning_rate=None, learning_rate_calibration=SPSALearningRateCalibrationConfig(...)) to derive the learning-rate scale from complete plus/minus directions at the initial point. The saved calibration contains the parameter order, direction evidence, averaged gradient, gradient RMS, target first-update RMS, derived scale, projection status, offsets, and actual cost. Fixed and calibrated scales are explicit alternatives. Calibration works with exact, exact-density, ideal sampled, and noisy sampled VQE, but does not tune perturbation, exponents, repeats, stopping thresholds, or claim convergence.
SPSAStoppingConfig optionally checks a complete iteration window online. The required checks cover center-proxy range, update norm, and averaged-gradient norm; direction-gradient and sampled-objective standard errors are optional. The first passing window uses termination.reason="stability_reached", then executes the normal final-center estimate. SPSAStoppingCheckIR, SPSAStoppingEvidenceIR, and derive_spsa_stopping_evidence() remain owner-package APIs in cascaqit.algorithms. The saved evidence is restorable and reportable, but it is not a convergence or optimality certificate.
Call result.diagnose_stability(VQEStabilityConfig(...)) on a completed native-SPSA VQE result to inspect terminal objective range, update norm, gradient norm, sampled uncertainty, repeat stops, and budget termination without rerunning the Backend. The result is stable, unstable, or insufficient_evidence for the selected optimizer start. Exact, ideal sampled, and noisy sampled results use the same saved statistics; the diagnosis does not correct noise bias. This is a configured engineering diagnosis, not a ground-state, global-optimum, or strict-convergence claim. Non-SPSA optimizers are not supported.
QAOA.gradient() and VQE.gradient() execute occurrence-level parameter-shift for affine RX/RY/RZ parameters. OptimizerConfig(method="L-BFGS-B", gradient=GradientConfig(...)) passes the same executable jacobian to SciPy; native Adam consumes the same gradient contract. Both save every ObjectiveGradientIR, shift Job, nfev, njev, and total Backend cost. QAOA gradients support ideal or exact-density noisy Digital execution. VQE additionally accepts PauliMeasurementConfig for ideal, noisy, or readout-mitigated finite-shot gradients and records their complete covariance. Sampled VQE gradients support fixed or bounded adaptive complete-gradient repeats. Their optional uncertainty target is
Here, Sigma denotes the complete parameter covariance matrix. Adam may combine that policy with a consecutive update-size and gradient-uncertainty stopping window. Sampled gradients and Adam remain VQE-only and do not support trajectory exact objectives, per-occurrence adaptive allocation, parallel shifts, Analog, or Hybrid execution.
The imports shown above are frequent workflow types. Paired-benchmark and stability-diagnostic configuration/result types are also root exports. Per-start diagnostic IR, run-level benchmark IR, gradient contracts, canonical Ansatz builders, Problem projections, decoding, and baseline helpers remain advanced exports from cascaqit.algorithms. See QAOA And VQE.
Unified Problem Compiler¶
from cascaqit.algorithms import OptimizerConfig
from cascaqit.problems import ProblemCompiler, ProblemExecutionResult
analysis = ProblemCompiler().analyze(problem, target=target)
compiled = ProblemCompiler().compile(
problem,
mode="hybrid",
algorithm="qaoa",
target=target,
)
execution = compiled.run(
params={"gamma_0": 0.2, "beta_0": 0.3},
shots=256,
seed=7,
)
optimized = compiled.optimize(
optimizer=OptimizerConfig(max_evaluations=24, starts=3, seed=7),
initial_parameters={"gamma_0": 0.2, "beta_0": 0.3},
shots=256,
seed=7,
)
ProblemCompiler uses one canonical Problem, logical Hamiltonian, Target-aware mapping plan, logical order, and decoder for all modes. It accepts digital + qaoa, digital + vqe, hybrid + qaoa, and analog + qaa. Digital QAOA and fixed-depth VQE produce Circuit; Unified VQE accepts the default template, HardwareEfficientAnsatz, CardinalityPreservingAnsatz, or a parameterized custom Circuit. Hybrid QAOA produces HybridProgram; Analog QAA produces AHSProgram. dad is the current Hybrid topology, while ahs is the Analog program model. Neither is passed as an algorithm or through a public strategy argument.
Compile results provide run(), evaluate(), parameter binding, result decoding, and two mutually exclusive optimize() forms: ordered caller-supplied points or configured continuous optimization. Every mode supports deterministic multiple starts; QAOA and built-in VQE also support layer-wise initialization. Digital QAOA/VQE compile results provide gradient() and L-BFGS-B, and Digital VQE also supports native Adam; Analog and Hybrid reject gradients before execution. ProblemCompiler.optimize_layers() runs one optimization per contiguous Digital QAOA/VQE or Hybrid QAOA depth and applies a fixed-budget improvement rule. Its finite-shot Digital VQE path requires SPSA or Adam plus independent candidate confirmation, uses confirmed energy for selection, and transfers the confirmed parameters. optimize_layers_repeated() runs independent complete optimizations at every depth, pairs later-layer warm starts by repeat index, and selects from a one-sided Student-t lower confidence bound. repeats is distinct from optimizer starts, shots, and trajectories; the optimizer seed remains None because the root experiment seed derives each run seed. ProblemLayerExperimentResult retains the single-run selection source and separate objective, confirmation, and final-sampling costs. ProblemRepeatedLayerExperimentResult retains every execution, layer statistic, paired comparison, selected depth, and stop reason. See Unified Problem Compiler.
Results¶
from cascaqit import build_counts_histogram, build_result_view
from cascaqit.results import InteractionReportIR, ResultEvidenceIR, ResultViewIR
from cascaqit.results import SimulationExecutionConfigIR, SimulationResourceUsageIR
Use these helpers to inspect counts, result evidence, diagnostics, run trace metadata, execution configuration, resource usage, and derived visualization-ready views. For a Digital program with one explicit measurement register, top-level counts, samples, probabilities, and bit ordering describe only that register; result.measurement() returns its typed record, while result.state_result retains the complete simulated state when the measurement is partial or reordered. Multiple registers require result.measurement(key) and build_counts_histogram(result, measurement_key=key) so the SDK never guesses which register to display. Local ResultIR.execution_config() returns SimulationExecutionConfigIR, and resource_usage() returns SimulationResourceUsageIR. interaction_report() returns the only executed Analog interaction report or None; use interaction_reports() for a Hybrid result with multiple Analog blocks. Each InteractionReportIR records the executed configuration, physical classification, geometry and pair-table hashes, active atom and enabled pair counts, distance/strength summary, and truthful state-evolution status. Scan aggregates expose execution and resource dictionaries in metadata; each completed scan item retains its own evidence. Pulser, hardware-mock, and cloud results do not synthesize these local planner facts.
Result helpers should be treated as consumers of ResultIR. ProgramIR and ResultIR remain the source of truth; result views, histograms, visualization metadata, and reports are derived views.
Standard Experiment Visualization¶
from cascaqit import visualize
report = visualize(result, program=program, output="experiment.html")
visualize() auto-detects Digital, Analog, Hybrid, Sweep, Comparison, Batch, VariationalResult, ProblemExecutionResult, ProblemLayerExperimentResult, and ProblemRepeatedLayerExperimentResult sources and returns an ExperimentReport. Single-result calls may include program context. Analog and Hybrid reports show atom geometry and status, active order, combined control waveforms, site-addressing frames, control schedules and diagnostics, phase-pattern design/runtime evidence, and numerical consumers. Algorithm reports consume existing objective, sampling, decode, baseline, complete Ansatz, and saved gradient evidence without rerunning optimization. Gradient views show the plan, components, L2 norm, shift energies, nfev/njev, and Backend cost. Problem reports add the canonical objective, logical Hamiltonian, penalty proof when defined, mapping, term assignment, generated Native Program, VQE Definition and circuit/spec hashes when applicable, candidate and expected energy decomposition, parameter history, and baseline from the stored execution context. A mapping of completed Problem results can compare layer counts, optimizer configurations, or Digital QAOA, Digital VQE, Hybrid QAOA, and Analog QAA routes when problem_hash and logical order match. Single-run layer reports show fixed-budget improvement evidence; repeated-layer reports add raw repeat objectives, Student-t intervals, paired lower bounds, run seeds, and complete optimization/evaluation cost. HTML is currently the only saved format.
ExperimentReport is owned by cascaqit.visualization; the root exposes only the high-frequency visualize entry. See Standard Experiment Visualization for report contents and boundaries.
Runtime And Backend Contracts¶
from cascaqit import LocalBackend
from cascaqit.backends import ExecutionBackendCapabilityProtocol
from cascaqit.backends import ExecutionBackendProtocol, ExecutionJobProtocol
from cascaqit.backends import ScanExecutionJobProtocol
LocalBackend and the optional PulserReferenceBackend satisfy the same single-run structural Protocol while retaining backend-specific capability IR. LocalBackend additionally provides aggregate scan contracts; aggregate scan results are LocalHybridScanJobResult, not single-run ResultIR values. LocalHybridExecutionBuilder remains available for custom state and bundle control, while JobRuntime and LocalHybridSimulator are internal or legacy-oriented paths rather than recommended user entrypoints.
Current backend-facing APIs are contracts and dry-run boundaries. They do not submit jobs to live Hanyuan hardware or CASCAQit Cloud.
These APIs do not access network endpoints, load credentials, read object-store artifact bytes, issue signed URLs, upload packages, or sign releases.
Offline Hardware Submission¶
Use CompilerPipeline from cascaqit.compiler to create ReferenceCompiledProgramIR, then use HardwareSubmissionBuilder from cascaqit.submission to build a checksummed HardwareSubmissionIR. The public package supports Digital and Analog contract construction only. It does not expose the private Compiler Service, execution package, hardware payload, Gateway, credentials, or endpoint.
See Offline Hardware Submission for a runnable example and the distinction between public compilation, contract construction, and the repository-only mock chain.
Interop¶
from cascaqit.interop import export_program, import_program, render_openqasm3_subset
from cascaqit.interop.openqasm3_subset import parse_openqasm3_subset
Restricted OpenQASM interop supports the local digital subset documented by the SDK. Unsupported grammar should be handled through diagnostics and explicit validation failures.
Full OpenQASM grammar, defcal, timing, and dynamic control are outside the current release scope.