Client API¶
fastqsim.client¶
FastQSim HTTP client.
Wraps all communication with the FastQubit REST API. Zero knowledge of quantum backends, parsers, or circuit objects — accepts only OpenQASM 3.0 strings and returns Job / Result / Session objects.
SDK version 0.1.1 — pod-token-only authentication (fqp_).
- class fastqsim.client.FastQSimClient(endpoint=None, token=None, execution_mode=None, timeout=300, max_retries=3)[source]¶
Bases:
objectPrimary interface for submitting and managing quantum simulation jobs on the FastQSim platform.
Instantiate via fastqsim.init() or directly:
client = FastQSimClient(endpoint=”https://api.qsim.io”)
- Parameters:
- cancel(job_ids)[source]¶
Request cancellation of one or more jobs.
Returns updated Job object(s). Raises JobCouldNotCancelError if the server rejects the cancellation.
- get(job_ids)[source]¶
Fetch the latest metadata for one or more jobs.
Returns a single Job when given a single ID, list otherwise.
- run(circuit, backend='qiskit', device='cpu', shots=1024, simulation_type=None, seed=None, metadata=None, asynchronous=False, job_name=None, options=None, tags=None)[source]¶
Submit one or more OpenQASM 3.0 circuits for simulation.
- Parameters:
circuit (
Union[str,List[str]]) – OpenQASM 3.0 string OR list of strings. Native circuit objects are NOT accepted.backend (
str) – ‘qiskit’, ‘cirq’, or ‘pennylane’.device (
str) – ‘cpu’, ‘gpu’, or ‘quantum’.shots (
int) – Number of measurement repetitions.simulation_type (
Optional[str]) – Simulation method to use. One of: - ‘statevector’ — full state-vector (default, all gates). - ‘density_matrix’ — open-system / noisy sim (all gates). - ‘mps’ — matrix product state (low-entanglement circuits). - ‘chp’ — stabilizer/Clifford (Clifford gates only). If None, the backend selects its default (statevector).seed (
Optional[int]) – RNG seed for reproducibility. Supported by all backends. When set, the same circuit produces identical counts on every run. When None, a fresh random seed is used.metadata (
Optional[Dict[str,Any]]) – Arbitrary key-value metadata stored with the job.asynchronous (
bool) – Return immediately (True) or block until done (False).job_name (
Optional[str]) – Human-readable label for the job.options (
Optional[Dict[str,Any]]) – Backend/device-specific options dict.tags (
Optional[Dict[str,Any]]) – Key-value tags attached to the job.
- Return type:
- Returns:
A single Job (or list of Jobs if circuit was a list).
- run_batch(circuits, backend='qiskit', device='cpu', shots=1024, max_parallel=10, simulation_type=None, seed=None, metadata=None, job_name=None, options=None, tags=None)[source]¶
Submit multiple OpenQASM 3.0 circuits as a batch.
All circuits share the same backend, device, shots, simulation_type, and seed. Batch jobs are always asynchronous — the server queues them and returns Job objects immediately. Use client.wait() to block.
- Parameters:
backend (
str) – Target backend for all circuits.device (
str) – Target device for all circuits.shots (
int) – Shots per circuit.max_parallel (
int) – Maximum circuits submitted concurrently (client-side threads).simulation_type (
Optional[str]) – Simulation method (‘statevector’, ‘density_matrix’, ‘mps’, ‘chp’). Applied to every circuit in the batch.metadata (
Optional[Dict[str,Any]]) – Key-value metadata stored with every job in the batch.job_name (
Optional[str]) – Label prefix applied to all jobs in the batch.options (
Optional[Dict[str,Any]]) – Backend/device-specific options applied to all circuits.tags (
Optional[Dict[str,Any]]) – Key-value tags attached to all jobs in the batch.
- Return type:
- Returns:
List of Job objects (one per circuit, preserving input order).
- search(run_status=None, created_later_than=None, limit=50, backend=None, start_date=None, end_date=None)[source]¶
Search jobs with optional filters.
- Parameters:
run_status (
Optional[str]) – Filter by status string (e.g. ‘completed’, ‘failed’).created_later_than (
Union[str,datetime,None]) – Only return jobs created after this datetime.limit (
int) – Maximum number of results to return (1–500).backend (
Optional[str]) – Filter by backend name (‘qiskit’, ‘cirq’, ‘pennylane’).start_date (
Optional[datetime]) – Filter by creation start date (inclusive).end_date (
Optional[datetime]) – Filter by creation end date (inclusive).
- Return type:
- Returns:
List of matching Job objects, most-recently-updated first.
- fastqsim.client.init(endpoint=None, token=None, execution_mode=None, timeout=300, max_retries=3)[source]¶
Initialise the global FastQSim client and return it.
The recommended usage is to call this with no arguments. The BFF or QCanvas injects runtime environment variables into the user-session pod, so the SDK picks them up without manual configuration:
client = fastqsim.init()
- Parameters:
endpoint (
Optional[str]) – Base API endpoint. Defaults to FASTQUBIT_ENDPOINT env var.token (
Optional[str]) – Pod-scoped session token (fqp_… format). Defaults to FASTQUBIT_SESSION_TOKEN env var.execution_mode (
Optional[str]) – ‘cloud’ or ‘local’. Defaults to FASTQSIM_EXECUTION_MODE env var or ‘cloud’.timeout (
int) – Per-request timeout in seconds.max_retries (
int) – Retry attempts for transient HTTP failures.
- Return type:
- Returns:
FastQSimClient instance (also stored as the global client).
- Raises:
AuthenticationError – No valid auth credential available.
FastQSimConnectionError – Cannot reach the API endpoint.
fastqsim package entry points¶
FastQSim SDK — public surface.
- Usage:
from fastqsim import FastQSimClient from fastqsim.types import Job, Result, Session, JobStatus, SimulationType, RunArgs from fastqsim.exceptions import FastQSimError, JobFailedError
- exception fastqsim.APIError[source]¶
Bases:
FastQSimErrorGeneral API error (API_001). Raised for unexpected server-side responses that do not map to a more specific SDK exception.
- exception fastqsim.AuthenticationError[source]¶
Bases:
FastQSimErrorRaised when the API token is invalid or expired (HTTP 401).
- class fastqsim.FastQSimClient(endpoint=None, token=None, execution_mode=None, timeout=300, max_retries=3)[source]¶
Bases:
objectPrimary interface for submitting and managing quantum simulation jobs on the FastQSim platform.
Instantiate via fastqsim.init() or directly:
client = FastQSimClient(endpoint=”https://api.qsim.io”)
- Parameters:
- cancel(job_ids)[source]¶
Request cancellation of one or more jobs.
Returns updated Job object(s). Raises JobCouldNotCancelError if the server rejects the cancellation.
- get(job_ids)[source]¶
Fetch the latest metadata for one or more jobs.
Returns a single Job when given a single ID, list otherwise.
- run(circuit, backend='qiskit', device='cpu', shots=1024, simulation_type=None, seed=None, metadata=None, asynchronous=False, job_name=None, options=None, tags=None)[source]¶
Submit one or more OpenQASM 3.0 circuits for simulation.
- Parameters:
circuit (
Union[str,List[str]]) – OpenQASM 3.0 string OR list of strings. Native circuit objects are NOT accepted.backend (
str) – ‘qiskit’, ‘cirq’, or ‘pennylane’.device (
str) – ‘cpu’, ‘gpu’, or ‘quantum’.shots (
int) – Number of measurement repetitions.simulation_type (
Optional[str]) – Simulation method to use. One of: - ‘statevector’ — full state-vector (default, all gates). - ‘density_matrix’ — open-system / noisy sim (all gates). - ‘mps’ — matrix product state (low-entanglement circuits). - ‘chp’ — stabilizer/Clifford (Clifford gates only). If None, the backend selects its default (statevector).seed (
Optional[int]) – RNG seed for reproducibility. Supported by all backends. When set, the same circuit produces identical counts on every run. When None, a fresh random seed is used.metadata (
Optional[Dict[str,Any]]) – Arbitrary key-value metadata stored with the job.asynchronous (
bool) – Return immediately (True) or block until done (False).job_name (
Optional[str]) – Human-readable label for the job.options (
Optional[Dict[str,Any]]) – Backend/device-specific options dict.tags (
Optional[Dict[str,Any]]) – Key-value tags attached to the job.
- Return type:
- Returns:
A single Job (or list of Jobs if circuit was a list).
- run_batch(circuits, backend='qiskit', device='cpu', shots=1024, max_parallel=10, simulation_type=None, seed=None, metadata=None, job_name=None, options=None, tags=None)[source]¶
Submit multiple OpenQASM 3.0 circuits as a batch.
All circuits share the same backend, device, shots, simulation_type, and seed. Batch jobs are always asynchronous — the server queues them and returns Job objects immediately. Use client.wait() to block.
- Parameters:
backend (
str) – Target backend for all circuits.device (
str) – Target device for all circuits.shots (
int) – Shots per circuit.max_parallel (
int) – Maximum circuits submitted concurrently (client-side threads).simulation_type (
Optional[str]) – Simulation method (‘statevector’, ‘density_matrix’, ‘mps’, ‘chp’). Applied to every circuit in the batch.metadata (
Optional[Dict[str,Any]]) – Key-value metadata stored with every job in the batch.job_name (
Optional[str]) – Label prefix applied to all jobs in the batch.options (
Optional[Dict[str,Any]]) – Backend/device-specific options applied to all circuits.tags (
Optional[Dict[str,Any]]) – Key-value tags attached to all jobs in the batch.
- Return type:
- Returns:
List of Job objects (one per circuit, preserving input order).
- search(run_status=None, created_later_than=None, limit=50, backend=None, start_date=None, end_date=None)[source]¶
Search jobs with optional filters.
- Parameters:
run_status (
Optional[str]) – Filter by status string (e.g. ‘completed’, ‘failed’).created_later_than (
Union[str,datetime,None]) – Only return jobs created after this datetime.limit (
int) – Maximum number of results to return (1–500).backend (
Optional[str]) – Filter by backend name (‘qiskit’, ‘cirq’, ‘pennylane’).start_date (
Optional[datetime]) – Filter by creation start date (inclusive).end_date (
Optional[datetime]) – Filter by creation end date (inclusive).
- Return type:
- Returns:
List of matching Job objects, most-recently-updated first.
- exception fastqsim.FastQSimConnectionError[source]¶
Bases:
FastQSimErrorRaised when the SDK cannot reach the FastQubit API endpoint.
- exception fastqsim.FastQSimError[source]¶
Bases:
ExceptionBase exception for all FastQSim SDK errors.
- exception fastqsim.InvalidDeviceTypeError[source]¶
Bases:
FastQSimErrorRaised when an unsupported or invalid device type is specified (VAL_002). Valid device types are: ‘cpu’, ‘gpu’, ‘quantum’.
- class fastqsim.Job(data, client=None)[source]¶
Bases:
objectRepresents a quantum simulation job submitted to the FastQSim platform.
Returned by FastQSimClient.run() and FastQSimClient.run_batch(). Call result() to block until completion and retrieve results, or use wait_for_completion() to poll and then inspect properties manually.
- Parameters:
data (Dict[str, Any])
client (Any)
- property billing_avg_memory_mb: float | None¶
average RSS memory usage in MB over execution.
- Type:
Billing telemetry
- property billing_cpu_millicore_seconds: float | None¶
integrated CPU usage in millicore-seconds.
- Type:
Billing telemetry
- property billing_memory_gb_seconds: float | None¶
integrated memory usage in GB-seconds.
- Type:
Billing telemetry
- property billing_memory_headroom_mb: float | None¶
memory headroom to pod limit in MB at completion.
- Type:
Billing telemetry
- property billing_psutil_available: bool | None¶
Whether psutil-based billing telemetry was available in the worker runtime.
- cancel()[source]¶
Request cancellation of a QUEUED or RUNNING job.
- Return type:
- Returns:
True if the cancellation was accepted.
- Raises:
JobCouldNotCancelError – Server rejected the cancellation request.
- property completed_at: datetime | None¶
When the worker finalized the terminal state in persistent storage.
- property cpu_seconds_total: float | None¶
Worker-reported process CPU time (user + system) consumed during execution.
- property error_message: str | None¶
Worker error message if the job failed. Contains the raw exception text from the Q-Pod (e.g. ParseError details).
- property execution_finished_at: datetime | None¶
Timestamp emitted by the q-worker after simulation and artifact upload.
- property execution_started_at: datetime | None¶
Timestamp emitted by the q-worker when simulation begins inside the pod.
- property execution_time_seconds: float | None¶
Worker-reported wall-clock execution duration in seconds.
- get_counts()[source]¶
Return measurement counts for a completed job.
- Raises:
JobNotCompleteError – Job has not finished yet.
JobDoesNotContainCountsError – Job was run without measurement shots.
- Return type:
- get_statevector()[source]¶
Retrieve the statevector for a completed job.
- Raises:
JobNotCompleteError – Job has not finished yet.
JobStatevectorTooLargeError – Statevector exceeds retrieval limit.
- Return type:
- property has_external_artifact: bool¶
True when the result was too large for inline storage and is persisted to S3. Use GET /jobs/{job_id}/result-url (client._fetch_external_artifact) to retrieve it.
- property num_qubits: int | None¶
Number of qubits in the circuit (from circuit profile). None until analyzer is wired.
- property options: Dict[str, Any]¶
Backend/device-specific execution options supplied at submission time.
- property peak_memory_mb: float | None¶
Worker-reported peak RSS memory usage in MB sampled during execution.
- property profile: Dict[str, Any]¶
Circuit complexity metrics extracted by the AST analyzer. Fields: qubit_count, depth, gate_count, two_qubit_gate_count. All None until the analyzer is implemented.
- property queue_dequeued_at: datetime | None¶
When the scheduler claimed the job and a worker pod was created.
- property queue_enqueued_at: datetime | None¶
When the job was accepted and published to the RabbitMQ queue.
- property resource_estimate: Dict[str, Any]¶
Predicted Kubernetes resource allocation for the worker pod. Fields: cpu_request, memory_request, cpu_limit, memory_limit. All None until adaptive sizing is implemented.
- result(timeout=None)[source]¶
Block until the job completes, then return the Result.
- Parameters:
timeout (
Optional[int]) – Maximum seconds to wait. Raises JobTimeoutError if exceeded.- Raises:
JobTimeoutError – Job did not complete within timeout.
JobFailedError – Job reached a failed terminal state.
- Return type:
- property result_counts: Dict[str, int] | None¶
Inline measurement counts (bit-string → count). Populated when job completes.
- property result_metadata: Dict[str, Any]¶
Additional result metadata emitted by the worker (backend name, simulation_type, engine version, etc.).
- property result_url_expires_at: datetime | None¶
Expiry of the last issued presigned result download URL.
- exception fastqsim.JobCouldNotCancelError(job_id, reason='')[source]¶
Bases:
FastQSimErrorRaised when a cancellation request is rejected by the server (e.g. the job has already completed or is in a non-cancellable state).
- exception fastqsim.JobDoesNotContainCountsError[source]¶
Bases:
FastQSimErrorRaised when get_counts() is called on a job that was run without measurement shots (e.g. statevector-only simulation).
- exception fastqsim.JobFailedError(job_id, reason='')[source]¶
Bases:
FastQSimErrorRaised when a job reaches FAILED status.
- job_id¶
The ID of the failed job.
- reason¶
The worker error message, if available.
- exception fastqsim.JobNotCompleteError(job_id, current_status='')[source]¶
Bases:
FastQSimErrorRaised when a result-retrieval method is called on a job that has not yet reached a terminal state (e.g. still RUNNING or QUEUED).
- exception fastqsim.JobNotFoundError(job_id)[source]¶
Bases:
FastQSimErrorRaised when a job_id does not exist on the server (HTTP 404).
- Parameters:
job_id (str)
- exception fastqsim.JobStatevectorTooLargeError[source]¶
Bases:
FastQSimErrorRaised when the statevector is too large to retrieve over the network (number of qubits exceeds the server-side retrieval limit).
- class fastqsim.JobStatus(value)[source]¶
-
All possible states a FastQSim job can be in.
Terminal states: completed, failed, cancelled Non-terminal: created, queued, running
- CANCELLED = 'cancelled'¶
- COMPLETED = 'completed'¶
- CREATED = 'created'¶
- FAILED = 'failed'¶
- QUEUED = 'queued'¶
- RUNNING = 'running'¶
- exception fastqsim.JobTimeoutError(job_id, timeout)[source]¶
Bases:
FastQSimErrorRaised when polling exceeds the configured timeout before the job reaches a terminal state.
- job_id¶
The ID of the job that timed out.
- timeout¶
The timeout in seconds that was exceeded.
- exception fastqsim.QuotaExceededError[source]¶
Bases:
FastQSimErrorRaised when the integrator’s concurrency or monthly quota is exhausted (HTTP 402).
- class fastqsim.Result(data)[source]¶
Bases:
objectSimulation results returned after a job reaches COMPLETED status.
Returned by Job.result() and Job.get_counts().
- Parameters:
data (Dict[str, Any])
- property counts: Dict[str, int]¶
512}.
- Type:
Measurement counts dictionary, e.g. {‘00’
- Type:
512, ‘11’
- property memory: List[str] | None¶
Individual shot results as bit-strings, e.g. [‘00’, ‘11’, ‘00’, …]. Only populated when the job was submitted with memory=True.
- class fastqsim.RunArgs(circuit, backend='qiskit', device='cpu', shots=1024, simulation_type=None, seed=None, metadata=None, job_name=None, options=None, tags=None)[source]¶
Bases:
objectOptional helper to construct job submission arguments.
Can be passed to FastQSimClient.run() instead of keyword arguments. All fields mirror the run() parameters exactly.
- Parameters:
- class fastqsim.Session(data, client=None)[source]¶
Bases:
objectRepresents a FastQubit session payload.
In pod-token SDK mode, session lifecycle operations are handled by the integrator control plane, so helper methods like refresh_token() and close() may raise ValidationError.
- Parameters:
data (Dict[str, Any])
client (Any)
- property already_active: bool | None¶
Present on POST /sessions/start responses only. True when an existing active session was returned because the per-user limit was already reached. False when a new session was provisioned.
- close()[source]¶
Terminate the session and release server-side resources.
Raises ValidationError in pod-token SDK mode.
- Return type:
- property execution_engine: str¶
Runtime engine used inside the user pod (e.g. ‘jupyter-kernel-gateway’).
- property expires_at: datetime | None¶
Hard TTL for this session. The pod is terminated after this time.
- property kernel_id: str | None¶
Jupyter kernel ID. Populated after the pod is ready. None for terminal sessions.
- property message: str | None¶
Human-readable note, e.g. instructions to terminate before starting a new session.
- refresh_token()[source]¶
Request a refreshed WebSocket authentication token from the server.
Raises ValidationError in pod-token SDK mode.
- Return type:
- class fastqsim.SimulationType(value)[source]¶
-
The simulation method used by the Q-Pod backend.
Determines both the physics model and the resource footprint:
STATEVECTOR: Full state-vector sim. Memory ∝ 2^N. Supports all gates.
DENSITY_MATRIX: Open-system sim with noise. Memory ∝ 4^N. Supports all gates.
MPS: Matrix Product State. Memory ∝ N·χ². Best for low-entanglement circuits.
CHP: Stabilizer / Clifford. Memory ∝ N². Clifford gates only (H, CNOT, S, measure).
- CHP = 'chp'¶
- DENSITY_MATRIX = 'density_matrix'¶
- MPS = 'mps'¶
- STATEVECTOR = 'statevector'¶
- exception fastqsim.UnauthorizedAccessError[source]¶
Bases:
FastQSimErrorRaised when the authenticated user lacks permission for a resource (HTTP 403).
- exception fastqsim.ValidationError[source]¶
Bases:
FastQSimErrorRaised when the submitted circuit or parameters fail server-side validation (HTTP 422).
- fastqsim.init(endpoint=None, token=None, execution_mode=None, timeout=300, max_retries=3)[source]¶
Initialise the global FastQSim client and return it.
The recommended usage is to call this with no arguments. The BFF or QCanvas injects runtime environment variables into the user-session pod, so the SDK picks them up without manual configuration:
client = fastqsim.init()
- Parameters:
endpoint (
Optional[str]) – Base API endpoint. Defaults to FASTQUBIT_ENDPOINT env var.token (
Optional[str]) – Pod-scoped session token (fqp_… format). Defaults to FASTQUBIT_SESSION_TOKEN env var.execution_mode (
Optional[str]) – ‘cloud’ or ‘local’. Defaults to FASTQSIM_EXECUTION_MODE env var or ‘cloud’.timeout (
int) – Per-request timeout in seconds.max_retries (
int) – Retry attempts for transient HTTP failures.
- Return type:
- Returns:
FastQSimClient instance (also stored as the global client).
- Raises:
AuthenticationError – No valid auth credential available.
FastQSimConnectionError – Cannot reach the API endpoint.